/// <summary> /// Transformes CAML xml fragment trough XSL stylesheet. /// </summary> /// <param name="caml">Source xml = CAML fragment</param> /// <param name="ti">Transformation</param> /// <returns>Transformed text</returns> public static string TransformCAML(XmlNode caml, TransformationInfo ti) { XslCompiledTransform xslTransform = new XslCompiledTransform(); // Read stylesheet code from transformation StringReader stream = new StringReader(ti.TransformationCode); XmlTextReader xmlReader = new XmlTextReader(stream); xslTransform.Load(xmlReader); // Create XMLDocument from CAML fragment XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(caml.InnerXml); StringWriter transformed = new StringWriter(); xslTransform.Transform(xmlDoc, null, transformed); return transformed.ToString(); }
public static object GetData(StageParams config) { XmlDocument input = Util.Validate<XmlDocument>( config.data, "XSLTStage" ); string xslPath = config.context.Server.MapPath( config.map ); if (!File.Exists(xslPath)) throw new FileLoadException(String.Format("Style sheet {0} is not found", xslPath)); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(xslPath, new XsltSettings(false, true), new XmlUrlResolver()); XsltArgumentList al = new XsltArgumentList(); int index = 0; foreach (XmlNode node in config.stage) if ( node.Attributes["type"] != null ) al.AddParam( node.Name, "", config.allParams[index++]); if (!config.last) { MemoryStream output = new MemoryStream(); transform.Transform(input, al, output); return output; } else { transform.Transform(input, al, config.outputStream); return null; } }
public static string Transform(string xsltFile, string xml, XsltArgumentList xslArg) { string result = ""; try { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(xsltFile); // XmlWriterSettings.OmitXmlDeclaration XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(new StringReader(xml)); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { xslt.Transform(xmlDoc, xslArg, writer); } sw.Flush(); result = sw.ToString(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return result; }
private static String ParseResponse(string response) { XmlDocument doc = null; XslCompiledTransform myXslTransform = null; TextWriter sw = null; string result; try { doc = new XmlDocument(); ; myXslTransform = new XslCompiledTransform(); sw = new StringWriter(); doc.LoadXml(response); myXslTransform.Load(new XmlTextReader(new StringReader(Resources.Resource.xml2json))); JavaScriptSerializer serializer = new JavaScriptSerializer(); myXslTransform.Transform(doc, null, sw); result = sw.ToString(); } catch { result = System.Web.Configuration.WebConfigurationManager.AppSettings["errorParsingOrLoading"]; logger.Error(result); } finally { sw.Close(); } return result; }
static void Main() { var xslt = new XslCompiledTransform(); xslt.Load(stylesheet); xslt.Transform(inputFile, outputFile); Console.WriteLine("HTML file saved to {0}", outputFile); }
static void Main() { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("../../../MusicCatalogue.xslt"); xslt.Transform("../../../MusicCatalogue.xml", "../../../14.MusicCatalogue.html"); Console.WriteLine("Successfully transformed!"); }
protected void imgSearchIcon_Click(object sender, ImageClickEventArgs e) { string helpCultureName = _cultureCookie != null ? _cultureCookie.Value : string.Empty; string rootUrl = HelpSiteMapProvider.GetProviderRootUrlByCultureName(helpCultureName); string contentIndexName = "HelpContentIndex:" + rootUrl; ContentIndex myContentIndex = null; ContentSearchResult mySearchResult = null; XmlDocument doc = new XmlDocument(); XslCompiledTransform xslt = new XslCompiledTransform(); XsltArgumentList xsltArgs = new XsltArgumentList(); StringWriter xsltResult = null; string exprPageTitle = @"(?si)(?:(?<=<meta\s*name\s*=\s*(?:""|')menuText(?:""|')\s*content\s*=\s*(?:""|'))(?<contentAttribute>.*?[^(?:"")]*)(?=(?:"")[^>]*>)|(?<=<meta\s*content\s*=\s*(?:""|'))(?<contentAttribute>.*?[^(?:"")]*)(?=(?:"")\s*name\s*=\s*(?:""|')menuText(?:""|')\s*[^>]*>))"; if (txtSearch.Text.Length > 0) { try { myContentIndex = Application[contentIndexName] as ContentIndex; if (myContentIndex == null) { myContentIndex = new ContentIndex(Page.MapPath(rootUrl), exprPageTitle); Application[contentIndexName] = myContentIndex; } mySearchResult = myContentIndex.Search(txtSearch.Text); doc.LoadXml(mySearchResult.ToXml()); xslt.Load(Server.MapPath("css/searchResult.xsl")); xsltArgs.AddParam("hrefPrefix", string.Empty, Request.Url.GetLeftPart(System.UriPartial.Path) + "?page=Help&content="); xsltArgs.AddParam("relativeURL", string.Empty, rootUrl); xsltArgs.AddParam("mappedURL", string.Empty, Page.MapPath(rootUrl)); xsltResult = new StringWriter(); xslt.Transform(doc, xsltArgs, xsltResult); litMainContent.Text = xsltResult.ToString(); } catch (XmlException xmlEx) { if (xmlEx.Message.ToLowerInvariant().Contains("root")) { //Missing root element. litMainContent.Text = String.Format(GetLocalResourceObject("NoContentFound").ToString(), txtSearch.Text); } else { litMainContent.Text = String.Format(GetLocalResourceObject("UnableToSearch").ToString(), xmlEx.Message); } } catch (Exception ex) { litMainContent.Text = String.Format(GetLocalResourceObject("UnableToSearch").ToString(), ex.Message); } finally { if (xsltResult != null) xsltResult.Close(); } } }
static void Main() { string originPathXslt = "../../../xml/catalogue.xslt"; string originPathXml = "../../../xml/catalogue.xml"; string destinationPath = "../../../xml/catalogue.html"; XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(originPathXslt); xslt.Transform(originPathXml, destinationPath); }
protected void ToExcel_Click(object sender, EventArgs e) { string json = ExcelGridData.Value.ToString(); StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null); XmlNode xml = eSubmit.Xml; this.Response.Clear(); this.Response.ContentType = "application/vnd.ms-excel"; this.Response.AddHeader("Content-Disposition", "attachment; filename=SaleRank.xls"); XslCompiledTransform xtExcel = new XslCompiledTransform(); xtExcel.Load(Server.MapPath("./Styles/Excel.xsl")); xtExcel.Transform(xml, null, this.Response.OutputStream); this.Response.End(); }
protected void Page_Load(object sender, EventArgs e) { Response.ContentType = "text/xml"; string xsltFile = Server.MapPath("books.xslt"); string xmlFile = Server.MapPath("books.xml"); XslCompiledTransform xslt = new XslCompiledTransform(true); //Pass in true to enable XSLT Debugging xslt.Load(xsltFile); XPathDocument doc = new XPathDocument(xmlFile); xslt.Transform(doc, new XmlTextWriter(Response.Output)); }
private XDocument TransformMarkup(XElement inputRoot) { var newTree = new XDocument(); using (XmlWriter writer = newTree.CreateWriter()) { var xslTransformer = new XslCompiledTransform(); xslTransformer.LoadFromPath(this.MapPath(XsltFileName)); xslTransformer.Transform(inputRoot.CreateReader(), writer); } return newTree; }
static void Main() { string decorationLine = new string('-', Console.WindowWidth); Console.Write(decorationLine); Console.WriteLine("***Transforming the XML document 'albums-catalogue.xml' to a HTML"); Console.WriteLine("file using 'albums-catalogue.xsl' stylesheet file with XSLT***"); Console.Write(decorationLine); XslCompiledTransform xslTransformer = new XslCompiledTransform(); xslTransformer.Load("../../albums-catalogue.xsl"); xslTransformer.Transform("../../albums-catalogue.xml", "../../albums-catalogue.html"); Console.WriteLine("Completed! You can see the HTML file in project's directory!"); }
public static void Transform(string sXmlPath, string sXslPath) { try { XPathDocument myXPathDoc = new XPathDocument(sXmlPath); XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(sXslPath); XsltArgumentList xslArgs = new XsltArgumentList(); Utils classPtr = new Utils(); xslArgs.AddExtensionObject("urn:util", classPtr); XmlTextWriter myWriter = new XmlTextWriter("result.xml", null); myXslTrans.Transform(myXPathDoc, xslArgs, myWriter); myWriter.Close(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } }
public CsvLoader(DirectoryInfo baseDir) { CsvDir = new DirectoryInfo(baseDir.FullName + '\\' + InputCsvDirName); if(!CsvDir.Exists){ throw new Exception(string.Format("Directory not found: {0}", CsvDir.FullName)); } OutputXmlDir = new DirectoryInfo(baseDir.FullName + '\\' + OutputXmlDirName); OutputHtmlDir = new DirectoryInfo(baseDir.FullName + '\\' + OutputHtmlDirName); InputXsltDir = new DirectoryInfo(baseDir.FullName + '\\' + InputXsltDirName); foreach(string s in XsltFileNames){ var xslt = new XslCompiledTransform(); FileInfo xsltFile = GetFileInfo(InputXsltDir, s + ".xsl"); xslt.Load(xsltFile.FullName); xslts.Add(s, xslt); } }
protected void Page_Load(object sender, EventArgs e) { string m = "<?xml version=\"1.0\"?>"; m += "<address>"; m += "<addressline1>" + "Veerannapet" + "</addressline1>"; m += "<addressline2>" + "Veerannapet2" + "</addressline2>"; m += "<city>" + "Mahabubnagar" + "</city>"; m += "<postcode>" + "509001" + "</postcode>"; m += "</address>"; string result1 = m.Replace("<?xml version=\"1.0\"?>", ""); XmlDocument docs = new XmlDocument(); docs.LoadXml(result1); string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(docs); XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "Report"); XslCompiledTransform xsl = new XslCompiledTransform(); StringWriter result = new StringWriter(); xsl.Load(Server.MapPath("Focus.xslt")); XmlTextWriter tx = new XmlTextWriter(result); XmlDeclaration xmldecl; xmldecl = doc.CreateXmlDeclaration("1.0", null, null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmldecl, root); //string strs = doc.InnerXml.ToString(); doc.WriteTo(tx); xsl.Transform(doc, null, tx); result.Close(); result.Flush(); string str = result.ToString(); // ... And the result you'll send back will be usable in a report: Response.ContentType = "text/xml"; Response.Write(str.ToString()); Response.Flush(); Response.Close(); }
public void Consume(string contentFolder, string siteFolder, string filename, string ext) { string contentFile = contentFolder + "/" + filename; string templateFile = GetTemplateFilename(filename, ext); SiteFile = siteFolder + "/index.html"; try { //XsltArgumentList xslArg = BuildXsltArgumentList(); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(templateFile); using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw)) { xslt.Transform(contentFile, XslArgs, writer); } sw.Flush(); Content = sw.ToString(); } } catch (Exception ex) { ReportError(templateFile, contentFile, ex); } }
//read in the blog posts from an RSS feed, using an XSLT stylesheet protected void LoadLatestBlogPosts() { try { string LatestBlogPostsRssUrl = System.Configuration.ConfigurationManager.AppSettings["LatestBlogPostsRssUrl"]; string LatestBlogPostsXslUrl = Server.MapPath(string.Format("xsl/{0}", ConfigurationManager.AppSettings["LatestBlogPostsXslFile"])); XmlDocument latestBlogPostsDoc = new XmlDocument(); XslCompiledTransform latestBlogPostsXsl = new XslCompiledTransform(); StringBuilder latestBlogPostsStringBuilder = new StringBuilder(); StringWriter latestBlogPostsStringWriter = new StringWriter(latestBlogPostsStringBuilder); latestBlogPostsDoc.Load(LatestBlogPostsRssUrl); latestBlogPostsXsl.Load(LatestBlogPostsXslUrl); latestBlogPostsXsl.Transform(latestBlogPostsDoc, null, latestBlogPostsStringWriter); //latestBlogPostsStringBuilder.Append("Cached at " + DateTime.Now.ToString()); LatestBlogPostsLiteral.Text = latestBlogPostsStringBuilder.ToString(); } catch (Exception ex) { //no op; since the .text assignment is the last line, then the section will simply not display if there are errors } }
public static MvcHtmlString RenderXslt(string xslPath, string xmlString, List<KeyValuePair<string, string>> parameters = null) { string xsltResult = string.Empty; try { // XML Settings XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.XmlResolver = null; xmlSettings.IgnoreComments = true; xmlSettings.DtdProcessing = DtdProcessing.Ignore; xmlSettings.ValidationType = ValidationType.None; // Attaches an action to the valiation event handler. This will write out error messages in the Output pane. #if DEBUG xmlSettings.ValidationEventHandler += (sender, e) => { Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message)); }; #endif // XSLT Settings XmlReaderSettings xsltSettings = new XmlReaderSettings(); xsltSettings.XmlResolver = null; xsltSettings.DtdProcessing = DtdProcessing.Ignore; xsltSettings.ValidationType = ValidationType.None; // Attaches an action to the valiation event handler. This will write out error messages in the Output pane. #if DEBUG xsltSettings.ValidationEventHandler += (sender, e) => { Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message)); }; #endif // Init params XsltArgumentList xslArgs = new XsltArgumentList(); if (parameters != null) { foreach (KeyValuePair<string, string> param in parameters) xslArgs.AddParam(param.Key, string.Empty, param.Value); } // Load XML using (XmlReader reader = XmlReader.Create(new StringReader(xmlString), xmlSettings)) { // Load XSL XsltSettings xslSettings = new XsltSettings(true, true); // Need to enable the document() fucntion using (XmlReader xslSource = XmlReader.Create(xslPath, xsltSettings)) { XslCompiledTransform xsltDoc = new XslCompiledTransform(); xsltDoc.Load(xslSource, xslSettings, new XmlUrlResolver()); // Transform using (var sw = new UTF8StringWriter()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.OmitXmlDeclaration = true; using (var xw = XmlWriter.Create(sw, settings)) { xsltDoc.Transform(reader, xslArgs, sw); } xsltResult = sw.ToString(); } } } } catch { } // custom error handling here // Return result return MvcHtmlString.Create(xsltResult); }
// Function : Export_with_XSLT_Web // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers response.Clear(); response.Buffer= true; if(FormatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek( 0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content response.Write(sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); response.End(); sw.Dispose(); stream.Dispose(); } catch(ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch(Exception Ex) { throw Ex; } }
/// <summary> /// Analyzes the object database /// </summary> /// <param name="FullPath">Full path of report file</param> /// <param name="FileName">Filename of report</param> /// <param name="Created">Time when report file was created</param> /// <param name="XmlOutput">XML Output</param> /// <param name="fs">File stream</param> /// <param name="Repair">If database should be repaired, if errors are found</param> /// <returns>Collections with errors found, and repaired if <paramref name="Repair"/>=true. If null, process could not be completed.</returns> public static async Task <string[]> DoAnalyze(string FullPath, string FileName, DateTime Created, XmlWriter XmlOutput, FileStream fs, bool Repair) { string[] Collections = null; try { Log.Informational("Starting analyzing database.", FileName); ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, 0, Created); Collections = await Database.Analyze(XmlOutput, Path.Combine(Gateway.AppDataFolder, "Transforms", "DbStatXmlToHtml.xslt"), Gateway.AppDataFolder, false, Repair); XmlOutput.Flush(); fs.Flush(); ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, fs.Length, Created); XmlOutput.Dispose(); XmlOutput = null; fs.Dispose(); fs = null; if (xslt is null) { xslt = XSL.LoadTransform(typeof(Gateway).Namespace + ".Transforms.DbStatXmlToHtml.xslt"); } string s = File.ReadAllText(FullPath); s = XSL.Transform(s, xslt); byte[] Bin = utf8Bom.GetBytes(s); string FullPath2 = FullPath.Substring(0, FullPath.Length - 4) + ".html"; File.WriteAllBytes(FullPath2, Bin); ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName.Substring(0, FileName.Length - 4) + ".html", Bin.Length, Created); Log.Informational("Database analysis successfully completed.", FileName); } catch (Exception ex) { Log.Critical(ex); string[] Tabs = ClientEvents.GetTabIDsForLocation("/Settings/Backup.md"); await ClientEvents.PushEvent(Tabs, "BackupFailed", "{\"fileName\":\"" + CommonTypes.JsonStringEncode(FileName) + "\", \"message\": \"" + CommonTypes.JsonStringEncode(ex.Message) + "\"}", true, "User"); } finally { try { XmlOutput?.Dispose(); fs?.Dispose(); } catch (Exception ex) { Log.Critical(ex); } lock (synchObject) { analyzing = false; } } return(Collections); }
public bool ValidateDocument(string validationType) { bool success = true; XmlDocument document = new XmlDocument(); try { if (validationType == "Xml") { document.LoadXml(editorUserControl.GetText()); } else if (validationType == "XSL") { XPathDocument xPathDoc = new XPathDocument(originalXmlFile); XslCompiledTransform xslTrans = new XslCompiledTransform(); XmlReader inputFile = XmlReader.Create(new StringReader(editorUserControl.GetText())); xslTrans.Load(inputFile); TextWriter tw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(tw); xslTrans.Transform(xPathDoc, null, writer); writer.Close(); } else if (validationType == "XSD") { if (String.IsNullOrEmpty(appliedXsdFile)) { Util.ShowMessage("No XSD file applied. Cannot validate."); success = false; } else { XmlReader xsdDoc = XmlReader.Create(appliedXsdFile); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(null, xsdDoc); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; readerSettings.ValidationEventHandler += XsdValidationCallBack; XmlReader reader = XmlReader.Create(new StringReader(editorUserControl.GetText()), readerSettings); while (reader.Read()) { } reader.Close(); success = !xsdError; xsdError = false; } } } catch (XsltException e) { success = false; SetEditorStatusTextBox(Util.GetDetailedErrorMessage(e)); editorUserControl.GotoLine(e.LineNumber, e.LinePosition); } catch (XmlException e) { success = false; if (validationType == "XSL") { Util.ShowMessage(string.Format("Error in Xml document: {0}\r\nPlease fix errors in the Xml document and try again.", Util.GetDetailedErrorMessage(e))); } else if (validationType == "XSD") { Util.ShowMessage(string.Format("Error in XSD document: {0}\r\nPlease fix errors in the XSD document and try again.", Util.GetDetailedErrorMessage(e))); } else { SetEditorStatusTextBox(Util.GetDetailedErrorMessage(e)); editorUserControl.GotoLine(e.LineNumber, e.LinePosition); } } catch (Exception e) { success = false; Util.ShowMessage(Util.GetDetailedErrorMessage(e)); } return(success); }
/// <summary> /// Fast means of constructing query using a cached,precompiled stylesheet /// </summary> public static XmlDocument GetQueryAsDOM(IDictionary <string, string> formProperties, XslCompiledTransform template) { XmlDocument result = new XmlDocument(); using (var stream = new MemoryStream()) { TransformCriteria(formProperties, template, stream); stream.Position = 0; result.Load(stream); } return(result); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param> private void btnSave_Click(object sender, RoutedEventArgs e) { try { if (VSIDEHelper.VisualStudioInstance.Solution.IsOpen) { if (0 == _reviewRepo.GetCount()) { return; } SolutionConfig solutionConfig = SolutionConfig.GetSolutionConfig(); if (solutionConfig == null) { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "html file (*.html)|*.html"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { _fileLocation = saveFileDialog1.FileName; // save user selected file location the solution config file solutionConfig = new SolutionConfig { ReviewPalFileLocation = _fileLocation }; solutionConfig.Save(); } } XmlSerializer s = new XmlSerializer(typeof(CodeReview)); string tmpFile = Path.GetTempFileName(); TextWriter w = new StreamWriter(tmpFile); _reviewRepo.AdjustReviewId(); s.Serialize(w, _reviewRepo.CodeReview); w.Close(); //load the Xml doc XPathDocument xPathDoc = new XPathDocument(tmpFile); File.Delete(tmpFile); XslCompiledTransform xslTrans = new XslCompiledTransform(); //load the Xsl xslTrans.Load(Utils.AssemblyPath + "\\" + "ReviewPal.xsl"); //create the output stream XmlTextWriter xmlWriter = new XmlTextWriter(_fileLocation, null); //do the actual transform of Xml xslTrans.Transform(xPathDoc, null, xmlWriter); xmlWriter.Close(); string xml = Utils.GetSerializedXml(_reviewRepo.CodeReview); // save the xml data as well within the html XmlDocument reviewHtml = new XmlDocument(); reviewHtml.Load(_fileLocation); XmlNode dataNode = CodeReview.GetDataNode(reviewHtml); dataNode.InnerXml = xml; reviewHtml.Save(_fileLocation); VSIDEHelper.VisualStudioInstance.StatusBar.Text = "Review List saved at " + _fileLocation + " successfully"; } else { MessageBox.Show(SolutionNotOpen); } } catch (Exception ex) { Utils.HandleException(ex); } }
/// <summary> /// Extends source elements in an open xml bibliography inside a Word document. /// </summary> /// <param name="docx"> /// Path to a Word document containing the bibliography. /// </param> /// <param name="stylesheet"> /// Path to the style used to generate the bibliography. /// </param> /// <returns> /// True if an extension took place, false otherwise. /// </returns> public static bool ExtendBibliography(string docx, string stylesheet) { // Counts the number of bibliographies in the current document which were transformed. int bibCnt = 0; // Open the docx package. Package package = Package.Open(docx, FileMode.Open, FileAccess.ReadWrite); try { // Go over every document in the package. foreach (PackageRelationship rel in package.GetRelationshipsByType(DocumentRelationshipType)) { // Get the uri indicating the document's location. Uri documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), rel.TargetUri); // Get the document. PackagePart document = package.GetPart(documentUri); // Go over every customXml file related to the document. foreach (PackageRelationship docRel in document.GetRelationshipsByType(CustomXmlRelationshipType)) { // Create the uri for a custom xml part of the document. Uri customXmlUri = PackUriHelper.ResolvePartUri(document.Uri, docRel.TargetUri); // Get the custom xml. PackagePart customXml = package.GetPart(customXmlUri); // Load the custom xml into an xml document. XmlDocument sources = new XmlDocument(); sources.Load(customXml.GetStream()); // Check if this is a custom xml describing a bibliography, i.e., check if it is a sources document. if (sources.DocumentElement.LocalName.ToLowerInvariant() == "sources" && sources.DocumentElement.NamespaceURI.ToLowerInvariant() == BibliographyNS.ToLowerInvariant()) { // Create an XML document to give to the XSL transformation. XmlDocument BibWordInput = new XmlDocument(); BibWordInput.AppendChild(BibWordInput.CreateXmlDeclaration("1.0", null, null)); // Give the XML document a b:BibOrder element as root. XmlElement rootElement = BibWordInput.CreateElement("b", "BibWord", BibliographyNS); BibWordInput.AppendChild(rootElement); // Attach all the b:Source elements from the sources document to the BibOrderInput document. XmlNamespaceManager nsm = new XmlNamespaceManager(sources.NameTable); nsm.AddNamespace("b", BibliographyNS); // A collection of source nodes before the transformation. XmlNodeList beforeTransform = sources.SelectNodes("//b:Sources/b:Source", nsm); foreach (XmlNode node in beforeTransform) { // Add the b:Source element to the XML document to transform. rootElement.AppendChild(BibWordInput.ImportNode(node, true)); } try { // Do the transformation. XmlDocument BibWordOutput = new XmlDocument(); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(stylesheet); using (XmlWriter writer = BibWordOutput.CreateNavigator().AppendChild()) { xslt.Transform(BibWordInput, (XsltArgumentList)null, writer); } // A collection of source nodes after the transformation. XmlNodeList afterTransform = BibWordOutput.SelectNodes("//b:BibWord/b:Source", nsm); // Only continu if no sources were lost. if (beforeTransform.Count == afterTransform.Count) { // Remove all nodes from the original document. foreach (XmlNode node in beforeTransform) { sources.DocumentElement.RemoveChild(node); } // Add the newly obtained b:Source elements back to the orignal document. foreach (XmlNode node in afterTransform) { sources.DocumentElement.AppendChild(sources.ImportNode(node, true)); } // Write the XML document back to the docx. StreamWriter sw = new StreamWriter(customXml.GetStream(FileMode.Create, FileAccess.ReadWrite)); sw.BaseStream.SetLength(0); // Fix for Mono. sw.Write(sources.OuterXml); sw.Flush(); sw.Close(); // Indicate that one more bibliography was transformed. bibCnt++; } else { throw new ArgumentException("Not a BibWord style.", stylesheet); } } catch (Exception) { // Close the docx package. package.Close(); // Rethrow the exception rather than returning failure. throw; } } } } } finally { // Close the docx package whatever happened. package.Close(); } // Give the user a hint that the extension was successful. return(bibCnt > 0); }
private void Transform() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Transforming: {0}", this.XmlFile)); XDocument xslDoc; if (!string.IsNullOrEmpty(this.XslTransformFile) && !File.Exists(this.XslTransformFile)) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XslTransformFile not found: {0}", this.XslTransformFile)); return; } if (!string.IsNullOrEmpty(this.XslTransformFile)) { // Load the XslTransformFile this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XslTransformFile: {0}", this.XslTransformFile)); xslDoc = XDocument.Load(this.XslTransformFile); } else if (!string.IsNullOrEmpty(this.XslTransform)) { // Load the XslTransform this.LogTaskMessage(MessageImportance.Low, "Loading XslTransform"); using (StringReader sr = new StringReader(this.XslTransform)) { xslDoc = XDocument.Load(sr); } } else { this.Log.LogError("XslTransform or XslTransformFile must be specified"); return; } // Load the style sheet. XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings { EnableScript = true }; using (StringReader sr = new StringReader(xslDoc.ToString())) { xslt.Load(XmlReader.Create(sr), settings, null); StringBuilder builder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(builder, xslt.OutputSettings)) { this.LogTaskMessage(MessageImportance.Low, "Running XslTransform"); // Execute the transform and output the results to a writer. xslt.Transform(this.xmlDoc.CreateReader(), writer); } this.Output = builder.ToString(); } if (!string.IsNullOrEmpty(this.OutputFile)) { if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Text) { this.LogTaskMessage(MessageImportance.Low, "Writing using text method"); using (FileStream stream = new FileStream(this.OutputFile, FileMode.Create)) { StreamWriter streamWriter = null; try { streamWriter = new StreamWriter(stream, Encoding.Default); // Output the results to a writer. streamWriter.Write(this.Output); } finally { if (streamWriter != null) { streamWriter.Close(); } } } } else { this.LogTaskMessage(MessageImportance.Low, "Writing using XML method"); using (StringReader sr = new StringReader(this.Output)) { XDocument newxmlDoc = XDocument.Load(sr); if (!string.IsNullOrEmpty(this.OutputFile)) { XmlWriterSettings writerSettings = new XmlWriterSettings { ConformanceLevel = this.conformanceLevel, Encoding = this.fileEncoding, Indent = this.Indent, OmitXmlDeclaration = this.OmitXmlDeclaration, CloseOutput = true }; using (XmlWriter xw = XmlWriter.Create(this.OutputFile, writerSettings)) { if (xw != null) { newxmlDoc.WriteTo(xw); } else { Log.LogError("There was an error creating the XmlWriter for the OutputFile"); return; } } } } } } }
/// <summary> /// Apply an XSLT transform on a file to produce a resulting file /// </summary> /// <param name="sTransformName">full path name of the XSLT transform</param> /// <param name="parameterList">list of parameters to pass to the transform</param> /// <param name="sInputPath">full path of the input file</param> /// <param name="sOutputName">full path of the resulting output file</param> public static void TransformFileToFile(string sTransformName, XSLParameter[] parameterList, string sInputPath, string sOutputName) { #if DEBUG Debug.WriteLine("Transform: " + sTransformName + " input file: " + sInputPath); DateTime start = DateTime.Now; Debug.WriteLine("\tStarting at: " + start.TimeOfDay.ToString()); #endif #if UsingDotNetTransforms // set up transform XslCompiledTransform transformer = new XslCompiledTransform(); transformer.Load(sTransformName); // add any parameters XsltArgumentList args; AddParameters(out args, parameterList); // setup output file using (var writer = File.CreateText(sOutputName)) { // load input file using (var reader = new XmlTextReader(sInputPath)) { #if NET_4_0 && !__MonoCS__ reader.DtdProcessing = DtdProcessing.Parse; #else reader.ProhibitDtd = false; #endif reader.EntityHandling = EntityHandling.ExpandEntities; // Apply transform transformer.Transform(reader, args, writer); } } #else // not UsingDotNetTransforms //.Net framework XML transform is still slower than something like MSXML2 // (this is so especially for transforms using xsl:key). MSXML2.XSLTemplate60Class xslt = new MSXML2.XSLTemplate60Class(); MSXML2.FreeThreadedDOMDocument60Class xslDoc = new MSXML2.FreeThreadedDOMDocument60Class(); MSXML2.DOMDocument60Class xmlDoc = new MSXML2.DOMDocument60Class(); MSXML2.IXSLProcessor xslProc; xslDoc.async = false; xslDoc.setProperty("ResolveExternals", true); xslDoc.setProperty("ProhibitDTD", false); xslDoc.load(sTransformName); xslt.stylesheet = xslDoc; xmlDoc.setProperty("ResolveExternals", true); xmlDoc.setProperty("ProhibitDTD", false); xmlDoc.async = false; xmlDoc.load(sInputPath); xslProc = xslt.createProcessor(); xslProc.input = xmlDoc; AddParameters(parameterList, xslProc); xslProc.transform(); StreamWriter sr = File.CreateText(sOutputName); sr.Write(xslProc.output); sr.Close(); #endif // UsingDotNetTransforms #if DEBUG DateTime end = DateTime.Now; Debug.WriteLine("\tEnding at: " + end.TimeOfDay.ToString()); System.TimeSpan diff = end.Subtract(start); Debug.WriteLine("\tProcess took: " + diff.ToString() + " " + sOutputName); #endif }
protected override int UpdateFeedItems(ISession session) { int result = 0; if (!string.IsNullOrEmpty(mFeed.Xsl)) { StringBuilder TransformedString = new StringBuilder(); XslCompiledTransform FeedXsl = new XslCompiledTransform(); FeedXsl.Load(new XmlTextReader(new StringReader(mFeed.Xsl)), null, null); StringWriter StringWriter = new StringWriter(TransformedString); XmlTextWriter TextWriter = new XmlTextWriter(StringWriter); FeedXsl.Transform(new XmlNodeReader(XmlFeed.DocumentElement), TextWriter); XmlFeed.LoadXml(TransformedString.ToString()); } XmlNodeList FeedXmlItems = XmlFeed.SelectNodes("descendant::channel/item"); List <FeedItem> updated = new List <FeedItem>(); foreach (XmlNode XmlNodeItem in FeedXmlItems) { XmlNode xmlLink = XmlNodeItem.SelectSingleNode("link"); string link = (xmlLink != null) ? xmlLink.InnerText : null; FeedItem current = null; if (!string.IsNullOrEmpty(link)) { for (int i = 0; i < mFeed.FeedItems.Count; i++) { FeedItem item = (FeedItem)mFeed.FeedItems[i]; if (item.Link == link) { current = item; updated.Add(item); mFeed.FeedItems.RemoveAt(i); break; } } } if (current == null) { result++; current = new FeedItem(); current.Feed = mFeed; current.Link = link; } XmlNode xmlDescription = XmlNodeItem.SelectSingleNode("description"); current.Description = (xmlDescription != null) ? xmlDescription.InnerText : null; XmlNode xmlTitle = XmlNodeItem.SelectSingleNode("title"); current.Title = (xmlTitle != null) ? xmlTitle.InnerText : null; session.Save(current); } foreach (FeedItem item in mFeed.FeedItems) { session.Delete(item); } mFeed.FeedItems = updated; return(result); }
static SQLExtenstions() { _queryPlanTransform = new XslCompiledTransform(); _queryPlanTransform.Load(Current.Context.Server.MapPath("~/Content/transforms/qp.xslt")); }
static void Main(string[] args) { string RootFolder = @"D:\VS\Project\FindOrgUa\constructor\"; string WwwFolder = RootFolder + @"www\"; string HtmlFolder = RootFolder + @"html\"; string XmlDataFile = RootFolder + @"xml\data.xml"; string XsltFile = RootFolder + @"xslt\template.xslt"; string XsltFileSitemap = RootFolder + @"xslt\sitemap.xslt"; //Sitemap Console.WriteLine("Create Sitemap"); XslCompiledTransform xsltSitemap = new XslCompiledTransform(); xsltSitemap.Load(XsltFileSitemap, new XsltSettings(true, true), null); XsltArgumentList xsltArgumentListSitemap = new XsltArgumentList(); xsltArgumentListSitemap.AddParam("DateTime", "", DateTime.Now.ToString("yyyy-MM-dd")); FileStream fileStreamSitemap = new FileStream(WwwFolder + "sitemap.xml", FileMode.Create); xsltSitemap.Transform(XmlDataFile, xsltArgumentListSitemap, fileStreamSitemap); xsltArgumentListSitemap = null; xsltSitemap = null; fileStreamSitemap = null; Console.WriteLine("OK"); // Console.WriteLine("Create pages"); XslCompiledTransform xsltGenerator = new XslCompiledTransform(); xsltGenerator.Load(XsltFile, new XsltSettings(true, true), null); XPathDocument xPathDoc = new XPathDocument(XmlDataFile); XPathNavigator xPathDocNavigator = xPathDoc.CreateNavigator(); XPathNodeIterator PageNodes = xPathDocNavigator.Select("/root/page"); while (PageNodes.MoveNext()) { XPathNavigator currentNode = PageNodes.Current; string titleNode = currentNode.SelectSingleNode("title").Value; string fileNode = currentNode.SelectSingleNode("file").Value; string menuactiveNode = currentNode.SelectSingleNode("menuactive").Value; Console.Write(fileNode); XsltArgumentList xsltArgumentList = new XsltArgumentList(); xsltArgumentList.AddParam("Title", "", titleNode); xsltArgumentList.AddParam("MenuActive", "", menuactiveNode); xsltArgumentList.AddParam("Body", "", File.ReadAllText(HtmlFolder + fileNode)); FileStream fileStream = new FileStream(WwwFolder + fileNode, FileMode.Create); xsltGenerator.Transform(XmlDataFile, xsltArgumentList, fileStream); fileStream = null; xsltArgumentList = null; Console.Write(" -> ok\n"); } Console.WriteLine("OK"); }
/// <summary> /// Run the generated XML file through the XSL transformation engine to create the file output. /// </summary> private void AsyncGenerateOutput(object sender, DoWorkEventArgs e) { string strXslPath = Path.Combine(Application.StartupPath, "sheets", _strSelectedSheet + ".xsl"); if (!File.Exists(strXslPath)) { string strReturn = string.Format("File not found when attempting to load {0}\n", _strSelectedSheet); Log.Enter(strReturn); MessageBox.Show(strReturn); return; } #if DEBUG XslCompiledTransform objXSLTransform = new XslCompiledTransform(true); #else XslCompiledTransform objXSLTransform = new XslCompiledTransform(); #endif try { objXSLTransform.Load(strXslPath); } catch (Exception ex) { string strReturn = string.Format("Error attempting to load {0}\n", _strSelectedSheet); Log.Enter(strReturn); Log.Error("ERROR Message = " + ex.Message); strReturn += ex.Message; MessageBox.Show(strReturn); return; } if (_workerOutputGenerator.CancellationPending) { e.Cancel = true; return; } MemoryStream objStream = new MemoryStream(); XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8); objXSLTransform.Transform(_objCharacterXML, objWriter); if (_workerOutputGenerator.CancellationPending) { e.Cancel = true; return; } objStream.Position = 0; // This reads from a static file, outputs to an HTML file, then has the browser read from that file. For debugging purposes. //objXSLTransform.Transform("D:\\temp\\print.xml", "D:\\temp\\output.htm"); //webBrowser1.Navigate("D:\\temp\\output.htm"); if (!GlobalOptions.PrintToFileFirst) { // Populate the browser using the DocumentStream. webBrowser1.DocumentStream = objStream; } else { // The DocumentStream method fails when using Wine, so we'll instead dump everything out a temporary HTML file, have the WebBrowser load that, then delete the temporary file. // Read in the resulting code and pass it to the browser. string strName = Guid.NewGuid().ToString() + ".htm"; StreamReader objReader = new StreamReader(objStream); string strOutput = objReader.ReadToEnd(); File.WriteAllText(strName, strOutput); string curDir = Directory.GetCurrentDirectory(); webBrowser1.Url = new Uri(String.Format("file:///{0}/" + strName, curDir)); File.Delete(strName); } }
public override bool transform() { // pretreat to the input .uof file of Presentation //preMethod(inputFile); FileStream fs = null; //XmlUrlResolver resourceResolver = null; XmlReader xr = null; string extractPath = Path.GetDirectoryName(outputFile) + Path.AltDirectorySeparatorChar; string prefix = this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + TranslatorConstants.UOFToOOX_POWERPOINT_LOCATION; string uof2ooxpre = extractPath + "uof2ooxpre.xml"; // 调用此部分出异常 所以改为下面语句 string picture_xml = "data"; // string uof2ooxpre = extractPath + "tmpDoc1.xml"; try { // copy XSLT templates Assembly asm = Assembly.GetExecutingAssembly(); foreach (string name in asm.GetManifestResourceNames()) { if (name.StartsWith(prefix)) { string filename = name.Substring(prefix.Length + 1); FileStream writer = new FileStream(extractPath + filename, FileMode.Create); Stream baseStream = asm.GetManifestResourceStream(name); int Length = 10240; Byte[] buffer = new Byte[Length]; int bytesRead = baseStream.Read(buffer, 0, Length); while (bytesRead > 0) { writer.Write(buffer, 0, bytesRead); bytesRead = baseStream.Read(buffer, 0, Length); } baseStream.Close(); writer.Close(); } } //resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(), prefix); //xr = XmlReader.Create(((ResourceResolver)resourceResolver).GetInnerStream("uof2oopre.xslt")); xr = XmlReader.Create(extractPath + "uof2ooxpre.xslt"); XPathDocument doc = new XPathDocument(extractPath + @"content.xml"); XslCompiledTransform transFrom = new XslCompiledTransform(); XsltSettings setting = new XsltSettings(true, false); XmlUrlResolver xur = new XmlUrlResolver(); transFrom.Load(xr, setting, xur); XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator(); // fs = new FileStream(outputFile, FileMode.Create); fs = new FileStream(uof2ooxpre, FileMode.Create); transFrom.Transform(nav, null, fs); fs.Close(); preMethod(uof2ooxpre); //ole对象lyy if (Directory.Exists(extractPath + "drawings") && Directory.Exists(extractPath + "embeddings")) { string tmpOle = extractPath + Path.AltDirectorySeparatorChar + "tmpOle.xml"; XmlDocument xdoc = new XmlDocument(); xdoc.Load(outputFile); XmlNameTable nt = xdoc.NameTable; XmlNamespaceManager nm = new XmlNamespaceManager(nt); nm.AddNamespace("w", TranslatorConstants.XMLNS_W); nm.AddNamespace("uof", TranslatorConstants.XMLNS_UOF); xdoc = OlePretreatment(xdoc, "uof:UOF", extractPath, nm); xdoc.Save(tmpOle); // OutputFilename = tmpPic; outputFile = tmpOle; } if (Directory.Exists(extractPath + picture_xml)) { string tmpPic = extractPath + Path.AltDirectorySeparatorChar + "tmpPic.xml"; XmlDocument xdoc = new XmlDocument(); xdoc.Load(outputFile); XmlNameTable nt = xdoc.NameTable; XmlNamespaceManager nm = new XmlNamespaceManager(nt); nm.AddNamespace("w", TranslatorConstants.XMLNS_W); nm.AddNamespace("uof", TranslatorConstants.XMLNS_UOF); xdoc = PicPretreatment(xdoc, "uof:UOF", extractPath + picture_xml, nm); xdoc.Save(tmpPic); // OutputFilename = tmpPic; outputFile = tmpPic; } //公式 if (File.Exists(extractPath + "equations.xml")) { string tmpEqu = extractPath + Path.AltDirectorySeparatorChar + "tmpEqu.xml"; string equXML = extractPath + "equations.xml"; XmlDocument equDoc = new XmlDocument(); equDoc.Load(equXML); XmlDocument xdoc = new XmlDocument(); xdoc.Load(outputFile); XmlNode equ = xdoc.ImportNode(equDoc.LastChild, true); xdoc.LastChild.AppendChild(equ); xdoc.Save(tmpEqu); outputFile = tmpEqu; } return(true); } catch (Exception ex) { logger.Error("Fail in Uof2.0 to OOX pretreatment1: " + ex.Message); logger.Error(ex.StackTrace); throw new Exception("Fail in Uof2.0 to OOX pretreatment1 of Presentation"); } finally { if (fs != null) { fs.Close(); } } }
public string ExecuteXSLTransformation(string xslt_filepath) { string ErrorMsg, HtmlTags = string.Empty, XsltPath; MemoryStream DataStream = default(MemoryStream); StreamReader streamReader = default(StreamReader); byte[] bytes = null; //Path of XSLT file XsltPath = HttpContext.Current.Server.MapPath(xslt_filepath); if (File.Exists(XsltPath)) { //Encode all Xml format string to bytes string strXML = GenerateXmlFormat(); if (strXML != string.Empty) { try { bytes = Encoding.UTF8.GetBytes(strXML); DataStream = new MemoryStream(bytes); //Create Xmlreader from memory stream XmlReader reader = XmlReader.Create(DataStream); // Load the XML XPathDocument document = new XPathDocument(reader); XslCompiledTransform XsltFormat = new XslCompiledTransform(); // Load the style sheet. XsltFormat.Load(XsltPath); DataStream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(DataStream, Encoding.UTF8); //Apply transformation from xml format to html format and save it in xmltextwriter XsltFormat.Transform(document, writer); streamReader = new StreamReader(DataStream); DataStream.Position = 0; HtmlTags = streamReader.ReadToEnd(); } catch (Exception ex) { ErrorMsg = ex.Message; return(ErrorMsg); } //finally //{ // //Release the resources // streamReader.Close(); // DataStream.Close(); //} } } return(HtmlTags); }
/// <summary> /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering. /// </summary> protected override void CreateChildControls() { SPSite mySite = SPContext.Current.Site; long maxLevel = 0; long usage = 0; SPSecurity.RunWithElevatedPrivileges(delegate { using (SPSite elevatedSite = new SPSite(mySite.ID)) { maxLevel = elevatedSite.Quota.StorageMaximumLevel; usage = elevatedSite.Usage.Storage; } }); //If there is not quota, no point in continuing if (maxLevel == 0) { return; } StringWriter sWriter = new StringWriter(); XmlTextWriter txWriter = new XmlTextWriter(sWriter); txWriter.WriteStartDocument(); txWriter.WriteStartElement("SPWeb"); txWriter.WriteElementString("StorageMaximumLeveL", maxLevel.ToString()); txWriter.WriteElementString("Storage", usage.ToString()); txWriter.WriteEndDocument(); txWriter.Flush(); txWriter.Close(); XmlDocument xmlInput = new XmlDocument(); xmlInput.LoadXml(sWriter.ToString()); XPathDocument xPathDoc; if (string.IsNullOrEmpty(XslText)) { Stream xsltStream = GetType().Assembly.GetManifestResourceStream("SiteQuotaWebPart.Default.xslt"); byte[] xsltBytes = new byte[xsltStream.Length]; xsltStream.Read(xsltBytes, 0, Convert.ToInt32(xsltStream.Length)); //StringWriter sWriter = new StringWriter(); //xsltStream.r XslText = Encoding.UTF8.GetString(xsltBytes); xsltStream.Seek(0, SeekOrigin.Begin); try { xPathDoc = new XPathDocument(xsltStream); } catch (XmlException ex) { Controls.Add(new LiteralControl(ex.Message)); return; } } else { //Skip the BOM from the string StringReader sReader = new StringReader(XslText.Substring(1)); // XmlTextReader xmlReader = new XmlTextReader(sReader); XmlReader xmlReader = XmlReader.Create(sReader); try { xPathDoc = new XPathDocument(xmlReader, XmlSpace.Default); } catch (XmlException ex) { Controls.Add(new LiteralControl(ex.Message)); return; } } XslCompiledTransform xmlTransform = new XslCompiledTransform(); xmlTransform.Load(xPathDoc); StringWriter outputWriter = new StringWriter(); XmlTextWriter xmlWriter = new XmlTextWriter(outputWriter); xmlTransform.Transform(xmlInput, xmlWriter); Controls.Add(new LiteralControl(outputWriter.ToString())); SetPersonalizationDirty(); base.CreateChildControls(); }
// TODO: XPathExpression可以缓存起来,加快速度 // 创建指定记录的浏览格式集合 // parameters: // domData 记录数据dom 不能为null // nStartCol 开始的列号。一般为0 // cols 浏览格式数组 // strError out参数,出错信息 // return: // -1 出错 // >=0 成功。数字值代表每个列包含的字符数之和 public int BuildCols(XmlDocument domData, int nStartCol, out string[] cols, out string strError) { strError = ""; cols = new string[0]; Debug.Assert(domData != null, "BuildCols()调用错误,domData参数不能为null。"); // 没有浏览格式定义时,就没有信息 if (this._dom == null) { return(0); } int nResultLength = 0; XPathNavigator nav = domData.CreateNavigator(); List <string> col_array = new List <string>(); if (this._dom.DocumentElement.Prefix == "") { // 得到xpath的值 // XmlNodeList nodeListXpath = this._dom.SelectNodes(@"//xpath"); XmlNodeList nodeListCol = this._dom.DocumentElement.SelectNodes("col"); CREATE_CACHE: // 创建Cache if (m_exprCache.Count == 0 && nodeListCol.Count > 0) { // 汇总需要创建的列名 this._useNames = GetUseColNames(); foreach (XmlElement nodeCol in nodeListCol) { CacheItem cache_item = new CacheItem(); m_exprCache[nodeCol] = cache_item; // XmlNode nodeXpath = nodeListXpath[i]; XmlElement nodeXPath = nodeCol.SelectSingleNode("xpath") as XmlElement; string strXpath = ""; if (nodeXPath != null) { strXpath = nodeXPath.InnerText.Trim(); } if (string.IsNullOrEmpty(strXpath) == false) { string strNstableName = DomUtil.GetAttrDiff(nodeXPath, "nstable"); XmlNamespaceManager nsmgr = (XmlNamespaceManager)this.tableNsClient[nodeXPath]; #if DEBUG if (nsmgr != null) { Debug.Assert(strNstableName != null, "此时应该没有定义'nstable'属性。"); } else { Debug.Assert(strNstableName == null, "此时必须没有定义'nstable'属性。"); } #endif XPathExpression expr = nav.Compile(strXpath); if (nsmgr != null) { expr.SetContext(nsmgr); } cache_item.expr = expr; } // 把 convert 参数也缓存起来 // XmlNode nodeCol = nodeXpath.ParentNode; string strConvert = DomUtil.GetAttr(nodeCol, "convert"); if (string.IsNullOrEmpty(strConvert) == false) { List <string> convert_methods = GetMethods(strConvert); cache_item.convert_methods = convert_methods; } else { cache_item.convert_methods = new List <string>(); } // 把 use 元素 text 缓存起来 XmlElement nodeUse = nodeCol.SelectSingleNode("use") as XmlElement; string strUse = ""; if (nodeUse != null) { strUse = nodeUse.InnerText.Trim(); } if (string.IsNullOrEmpty(strUse) == false) { cache_item.Use = strUse; } } } Dictionary <string, MarcColumn> results = null; string filter = this._dom.DocumentElement.GetAttribute("filter"); if (filter == "marc" && this._useNames.Count > 0) { results = MarcBrowse.Build(domData, this._useNames); } foreach (XmlElement nodeCol in nodeListCol) { #if NO XmlNode nodeXpath = nodeListXpath[i]; string strXpath = nodeXpath.InnerText.Trim(); // 2012/2/16 if (string.IsNullOrEmpty(strXpath) == true) { continue; } // 优化速度 2014/1/29 XmlNode nodeCol = nodeXpath.ParentNode; #endif CacheItem cache_item = m_exprCache[nodeCol] as CacheItem; List <string> convert_methods = cache_item.convert_methods; if (convert_methods == null) { Debug.Assert(false, ""); string strConvert = DomUtil.GetAttr(nodeCol, "convert"); convert_methods = GetMethods(strConvert); } string strText = ""; XPathExpression expr = cache_item.expr; if (expr != null) { if (expr == null) { #if NO this.m_exprCache.Clear(); this.m_methodsCache.Clear(); goto CREATE_CACHE; // TODO: 如何预防死循环? #endif } Debug.Assert(expr != null, ""); if (expr.ReturnType == XPathResultType.Number) { strText = nav.Evaluate(expr).ToString();//Convert.ToString((int)(nav.Evaluate(expr))); strText = ConvertText(convert_methods, strText); } else if (expr.ReturnType == XPathResultType.Boolean) { strText = Convert.ToString((bool)(nav.Evaluate(expr))); strText = ConvertText(convert_methods, strText); } else if (expr.ReturnType == XPathResultType.String) { strText = (string)(nav.Evaluate(expr)); strText = ConvertText(convert_methods, strText); } else if (expr.ReturnType == XPathResultType.NodeSet) { // 看看是否要插入什么分隔符 string strSep = GetSepString(convert_methods); XPathNodeIterator iterator = nav.Select(expr); StringBuilder text = new StringBuilder(4096); while (iterator.MoveNext()) { XPathNavigator navigator = iterator.Current; string strOneText = navigator.Value; if (strOneText == "") { continue; } strOneText = ConvertText(convert_methods, strOneText); // 加入分隔符号 if (text.Length > 0 && string.IsNullOrEmpty(strSep) == false) { text.Append(strSep); } text.Append(strOneText); } strText = text.ToString(); } else { strError = "XPathExpression的ReturnType为'" + expr.ReturnType.ToString() + "'无效"; return(-1); } } if (string.IsNullOrEmpty(cache_item.Use) == false) { MarcColumn column = null; results.TryGetValue(cache_item.Use, out column); if (column != null && string.IsNullOrEmpty(column.Value) == false) { strText += column.Value; } } // 空内容也要算作一列 // 2008/12/18 col_array.Add(strText); nResultLength += strText.Length; } } else if (this._dom.DocumentElement.Prefix == "xsl") { if (this.m_xt == null) { // <col>元素下的<title>元素要去掉 XmlDocument temp = new XmlDocument(); temp.LoadXml(this._dom.OuterXml); XmlNodeList nodes = temp.DocumentElement.SelectNodes("//col/title"); foreach (XmlNode node in nodes) { node.ParentNode.RemoveChild(node); } XmlReader xr = new XmlNodeReader(temp); // 把xsl加到XslTransform XslCompiledTransform xt = new XslCompiledTransform(); // 2006/10/26 changed xt.Load(xr /*, new XmlUrlResolver(), null*/); this.m_xt = xt; } // 输出到的地方 string strResultXml = ""; using (TextWriter tw = new StringWriter()) using (XmlTextWriter xw = new XmlTextWriter(tw)) { //执行转换 this.m_xt.Transform(domData.CreateNavigator(), /*null,*/ xw /*, null*/); // tw.Close(); tw.Flush(); // 2015/11/24 增加此句 strResultXml = tw.ToString(); } XmlDocument resultDom = new XmlDocument(); try { if (string.IsNullOrEmpty(strResultXml) == false) { resultDom.LoadXml(strResultXml); } else { resultDom.LoadXml("<root />"); } } catch (Exception ex) { strError = "browse 角色文件生成的结果文件加载到 XMLDOM 时出错:" + ex.Message; return(-1); } XmlNodeList colList = resultDom.DocumentElement.SelectNodes("//col"); foreach (XmlNode colNode in colList) { string strColText = colNode.InnerText.Trim(); // 2012/2/16 // 2008/12/18 string strConvert = DomUtil.GetAttr(colNode, "convert"); List <string> convert_methods = GetMethods(strConvert); // 2008/12/18 if (String.IsNullOrEmpty(strConvert) == false) { strColText = ConvertText(convert_methods, strColText); } //if (strColText != "") //空内容也要算作一列 col_array.Add(strColText); nResultLength += strColText.Length; } } else { strError = "browse 角色文件的根元素的前缀'" + this._dom.DocumentElement.Prefix + "'不合法。"; return(-1); } // 把col_array转到cols里 cols = new string[col_array.Count + nStartCol]; col_array.CopyTo(cols, nStartCol); // cols = ConvertUtil.GetStringArray(nStartCol, col_array); return(nResultLength); }
/// <summary> /// Fast transformation using a pre-compiled stylesheet (suitable for production environments) /// </summary> public static void TransformCriteria(IDictionary <string, string> formProperties, XslCompiledTransform transformer, Stream result) { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("Document"); doc.AppendChild(root); foreach (var prop in formProperties) { string propName = prop.Key; string value = prop.Value; if ((value != null) && (value.Length > 0)) { DOMUtils.InsertChild(root, propName, value); } } transformer.Transform(doc, null, result); }
public static string GenerateNewsletter(CUSTOMER Customer, List <CAMPAIGN> Campaigns, List <CAMPAIGN> FutureCampaigns) { // Input data will be defined in this XML document. XmlDocument xmlDoc = new XmlDocument(); XmlElement xmlRoot; XmlNode xmlNode, xmlNode2; XmlNode xmlChild, xmlChild2; xmlDoc.LoadXml( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<Root>" + //"<UserName/>" + //"<Message/>" + "<Campaigns/>" + "<FutureCampaigns/>" + "<UnsubscribeUrl/>" + "</Root>"); // Set the values of the XML nodes that will be used by XSLT. xmlRoot = xmlDoc.DocumentElement; //xmlNode = xmlRoot.SelectSingleNode("/Root/UserName"); //string prefix = (Customer.Gender == "M" ? "I " : "E "); //xmlNode.InnerText = prefix + "dashur " + Customer.Name + " " + Customer.Surname; //xmlNode = xmlRoot.SelectSingleNode("/Root/Message"); //xmlNode.InnerText = Configuration.NewsletterHeaderText; xmlNode = xmlRoot.SelectSingleNode("/Root/Campaigns"); foreach (CAMPAIGN campaign in Campaigns) { xmlChild = xmlDoc.CreateNode(XmlNodeType.Element, "Campaign", null); // title xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Title", null); xmlChild2.InnerText = campaign.BrandName; xmlChild.AppendChild(xmlChild2); // from //xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "From", null); //xmlChild2.InnerText = campaign.StartDate.ToString("dd/MM/yyyy"); //xmlChild.AppendChild(xmlChild2); // to xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "To", null); xmlChild2.InnerText = campaign.EndDate.ToString("dd/MM/yyyy"); xmlChild.AppendChild(xmlChild2); // image xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Image", null); xmlChild2.InnerText = Configuration.DeploymentURL + Configuration.ImagesUploadPath + campaign.ImageHome; xmlChild.AppendChild(xmlChild2); // Url xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Url", null); xmlChild2.InnerText = Configuration.DeploymentURL + "/campaign/" + Encryption.Encrypt(campaign.ID.ToString()); xmlChild.AppendChild(xmlChild2); xmlNode.AppendChild(xmlChild); } if (FutureCampaigns != null && FutureCampaigns.Count > 0) { xmlNode2 = xmlRoot.SelectSingleNode("/Root/FutureCampaigns"); foreach (CAMPAIGN campaign in FutureCampaigns) { xmlChild = xmlDoc.CreateNode(XmlNodeType.Element, "Campaign", null); // title xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Title", null); xmlChild2.InnerText = campaign.BrandName; xmlChild.AppendChild(xmlChild2); // from xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "From", null); xmlChild2.InnerText = campaign.StartDate.ToString("dd/MM/yyyy"); xmlChild.AppendChild(xmlChild2); // to xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "To", null); xmlChild2.InnerText = campaign.EndDate.ToString("dd/MM/yyyy"); xmlChild.AppendChild(xmlChild2); // image xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Image", null); xmlChild2.InnerText = Configuration.DeploymentURL + Configuration.ImagesUploadPath + campaign.ImageHome; xmlChild.AppendChild(xmlChild2); // Url xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Url", null); xmlChild2.InnerText = Configuration.DeploymentURL; // +"/campaign/" + Encryption.Encrypt(campaign.ID.ToString()); xmlChild.AppendChild(xmlChild2); xmlNode2.AppendChild(xmlChild); } } //xmlNode = xmlRoot.SelectSingleNode("/Root/UnsubscribeUrl"); //xmlNode.InnerText = Configuration.UnsubscribeUrl + Encryption.Encrypt(Customer.ID.ToString()); // This is our XSL template. XslCompiledTransform xslDoc = new XslCompiledTransform(); xslDoc.Load(@Configuration.NewsletterTemplate); XsltArgumentList xslArgs = new XsltArgumentList(); StringWriter writer = new StringWriter(); // Merge XSLT document with data XML document // (writer will hold resulted transformation). xslDoc.Transform(xmlDoc, xslArgs, writer); return(writer.ToString()); }
public static void DeployPerspectives(ProjectItem projItem, DTE2 ApplicationObject) { Microsoft.AnalysisServices.Cube oCube = (Microsoft.AnalysisServices.Cube)projItem.Object; if (oCube.Perspectives.Count == 0) { MessageBox.Show("There are no perspectives defined in this cube yet."); return; } try { ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy); ApplicationObject.StatusBar.Progress(true, "Deploying perspectives", 1, 5); FileAttributes fa = System.IO.File.GetAttributes(projItem.get_FileNames(1)); if ((fa & FileAttributes.ReadOnly) != FileAttributes.ReadOnly) { //Save the cube projItem.Save(""); } ApplicationObject.StatusBar.Progress(true, "Deploying perspectives", 2, 5); // extract deployment information DeploymentSettings deploySet = new DeploymentSettings(projItem); // use xlst to create xmla alter command XslCompiledTransform xslt = new XslCompiledTransform(); XmlReader xsltRdr; XmlReader xrdr; // read xslt from embedded resource xsltRdr = XmlReader.Create(new StringReader(BIDSHelper.Resources.Common.DeployPerspectives)); using ((xsltRdr)) { // read content from .cube file xrdr = XmlReader.Create(projItem.get_FileNames(1)); using (xrdr) { ApplicationObject.StatusBar.Progress(true, "Deploying perspectives", 3, 5); // Connect to Analysis Services Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server(); svr.Connect(deploySet.TargetServer); ApplicationObject.StatusBar.Progress(true, "Deploying perspectives", 4, 5); // execute the xmla try { // Build up the Alter perspectives command using XSLT against the .cube file XslCompiledTransform xslta = new XslCompiledTransform(); StringBuilder sb = new StringBuilder(); XmlWriterSettings xws = new XmlWriterSettings(); xws.OmitXmlDeclaration = true; xws.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter xwrtr = XmlWriter.Create(sb, xws); xslta.Load(xsltRdr); XsltArgumentList xslarg = new XsltArgumentList(); Database targetDB = svr.Databases.FindByName(deploySet.TargetDatabase); if (targetDB == null) { throw new System.Exception(string.Format("A database called {0} could not be found on the {1} server", deploySet.TargetDatabase, deploySet.TargetServer)); } string targetDatabaseID = targetDB.ID; xslarg.AddParam("TargetDatabase", "", targetDatabaseID); xslta.Transform(xrdr, xslarg, xwrtr); Cube oServerCube = targetDB.Cubes.Find(oCube.ID); if (oServerCube == null) { throw new System.Exception(string.Format("The {0} cube is not yet deployed to the {1} server.", oCube.Name, deploySet.TargetServer)); } //drop any perspectives which don't exist svr.CaptureXml = true; for (int i = 0; i < oServerCube.Perspectives.Count; i++) { Perspective p = oServerCube.Perspectives[i]; if (!oCube.Perspectives.Contains(p.ID)) { p.Drop(); i--; } } svr.CaptureXml = false; try { if (svr.CaptureLog.Count > 0) { svr.ExecuteCaptureLog(true, false); } } catch (System.Exception ex) { throw new System.Exception("Error dropping perspective that were deleted in the source code. " + ex.Message); } // update the perspectives XmlaResultCollection xmlaRC = svr.Execute(sb.ToString()); StringBuilder sbErr = new StringBuilder(); for (int iRC = 0; iRC < xmlaRC.Count; iRC++) { for (int iMsg = 0; iMsg < xmlaRC[iRC].Messages.Count; iMsg++) { sbErr.AppendLine(xmlaRC[iRC].Messages[iMsg].Description); } } if (sbErr.Length > 0) { MessageBox.Show(sbErr.ToString(), "BIDSHelper - Deploy Perspectives"); } try { // Building the project means that the .asdatabase file gets re-built so that // we do not break the Deployment Wizard. projItem.DTE.Solution.SolutionBuild.BuildProject(projItem.DTE.Solution.SolutionBuild.ActiveConfiguration.Name, projItem.ContainingProject.UniqueName, false); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } catch (System.Exception ex) { if (MessageBox.Show("The following error occured while trying to deploy the perspectives\r\n" + ex.Message + "\r\n\r\nDo you want to see a stack trace?" , "BIDS Helper - Deploy Perspectives" , MessageBoxButtons.YesNo , MessageBoxIcon.Error , MessageBoxDefaultButton.Button2) == DialogResult.Yes) { MessageBox.Show(ex.StackTrace); } } finally { ApplicationObject.StatusBar.Progress(true, "Deploying perspectives", 5, 5); // report any results back (status bar?) svr.Disconnect(); } } } } finally { ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy); ApplicationObject.StatusBar.Progress(false, "Deploying perspectives", 5, 5); } }
protected void Page_Load(object sender, EventArgs e) { string username = Convert.ToString(Session["username"]); Label1.Text = "Welcome" + " " + " " + username; if (!IsPostBack) { // The page is being loaded and accessed for the first time. // Retrieve user input from the form. if (Request.QueryString["s"] == null) // Set the default stock symbol to YHOO. m_symbol = "YHOO"; else // Get the user's input. m_symbol = Request.QueryString["s"].ToString().ToUpper(); // Update the textbox value. txtSymbol.Value = m_symbol; // This DIV that contains text and DIVs that displays stock quotes and chart from Yahoo. // Set the innerHTML property to replaces the existing content of the DIV. divService.InnerHtml = "<br />"; if (m_symbol.Trim() != "") { try { // Return the stock quote data in XML format. String arg = GetQuote(m_symbol.Trim()); if (arg == null) return; // Read XML. // Declare an XmlDocument object to represents an XML document. XmlDocument xd = new XmlDocument(); // Loads the XML data from a stream. xd.LoadXml(arg); // Read XSLT // Declare an XslCompiledTransform object to transform XML data using an XSLT style sheet. XslCompiledTransform xslt = new XslCompiledTransform(); // Use the Load method to load the Xsl transform object. xslt.Load(Server.MapPath("stock.xsl")); // Transform the XML document into HTML. StringWriter fs = new StringWriter(); xslt.Transform(xd.CreateNavigator(), null, fs); string result = fs.ToString(); // Replace the characters ">" and "<" back to "<" and ">". divService.InnerHtml = "<br />" + result.Replace("<", "<").Replace(">", ">") + "<br />"; // Display stock charts. String[] symbols = m_symbol.Replace(",", " ").Split(' '); // Loop through each stock for (int i = 0; i < symbols.Length; ++i) { if (symbols[i].Trim() == "") continue; int index = divService.InnerHtml.ToLower().IndexOf(symbols[i].Trim().ToLower() + " is invalid."); // If index = -1, the stock symbol is valid. if (index == -1) { // Use a random number to defeat cache. Random random = new Random(); divService.InnerHtml += "<img id='imgChart_" + i.ToString() + "' src='http://ichart.finance.yahoo.com/b?s=" + symbols[i].Trim().ToUpper() + "& " + random.Next() + "' border=0><br />"; // 1 days divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(0," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div1d_" + i.ToString() + "'><b>1d</b></span></a> "; // 5 days divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(1," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div5d_" + i.ToString() + "'>5d</span></a> "; // 3 months divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(2," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div3m_" + i.ToString() + "'>3m</span></a> "; // 6 months divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(3," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div6m_" + i.ToString() + "'>6m</span></a> "; // 1 yeas divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(4," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div1y_" + i.ToString() + "'>1y</span></a> "; // 2 years divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(5," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div2y_" + i.ToString() + "'>2y</span></a> "; // 5 years divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(6," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div5y_" + i.ToString() + "'>5y</span></a> "; // Max divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(7," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='divMax_" + i.ToString() + "'>Max</span></a><br><br /><br /> "; } } } catch { // Handle exceptions } } } }
public static string GenerateBonusMail(CUSTOMER Customer) { // Input data will be defined in this XML document. XmlDocument xmlDoc = new XmlDocument(); XmlElement xmlRoot; XmlNode xmlNode, xmlChild2, xmlChild, xmlNode3; xmlDoc.LoadXml( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<Root>" + "<Customer/>" + "<Invited/>" + "<Bonus/>" + "<Url/>" + "<Campaigns/>" + "</Root>"); // Set the values of the XML nodes that will be used by XSLT. xmlRoot = xmlDoc.DocumentElement; xmlNode = xmlRoot.SelectSingleNode("/Root/Customer"); xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Name", null); xmlChild2.InnerText = Customer.CUSTOMER2.Name + " " + Customer.CUSTOMER2.Surname; xmlNode.AppendChild(xmlChild2); xmlNode = xmlRoot.SelectSingleNode("/Root/Url"); xmlNode.InnerText = Configuration.DeploymentURL; xmlNode = xmlRoot.SelectSingleNode("/Root/Invited"); xmlNode.InnerText = Customer.Email; xmlNode = xmlRoot.SelectSingleNode("/Root/Bonus"); xmlNode.InnerText = Configuration.BonusValue.ToString() + " €"; xmlNode3 = xmlRoot.SelectSingleNode("/Root/Campaigns"); CAMPAIGN searchCampaign = new CAMPAIGN() { Active = true, Approved = true }; int TotalCampaignsForToday; List <CAMPAIGN> campaigns = ApplicationContext.Current.Campaigns.Search(searchCampaign, 100, 0, out TotalCampaignsForToday, "StartDate", BL.Util.SortDirection.Descending); string path; foreach (CAMPAIGN campaign in campaigns) { xmlChild = xmlDoc.CreateNode(XmlNodeType.Element, "Campaign", null); // title xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Title", null); xmlChild2.InnerText = campaign.BrandName; xmlChild.AppendChild(xmlChild2); // from //xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "From", null); //xmlChild2.InnerText = campaign.StartDate.ToString("dd/MM/yyyy"); //xmlChild.AppendChild(xmlChild2); // to xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "To", null); xmlChild2.InnerText = campaign.EndDate.ToString("dd/MM/yyyy"); xmlChild.AppendChild(xmlChild2); // image xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Image", null); if (Configuration.ImagesVisualizationPath.Contains(Configuration.DeploymentURL)) { path = Configuration.ImagesVisualizationPath; } else { path = Configuration.DeploymentURL + Configuration.ImagesVisualizationPath; } xmlChild2.InnerText = path + campaign.ImageHome; xmlChild.AppendChild(xmlChild2); // Url xmlChild2 = xmlDoc.CreateNode(XmlNodeType.Element, "Url", null); xmlChild2.InnerText = Configuration.DeploymentURL + "/campaign/" + Encryption.Encrypt(campaign.ID.ToString()); xmlChild.AppendChild(xmlChild2); xmlNode3.AppendChild(xmlChild); } // This is our XSL template. XslCompiledTransform xslDoc = new XslCompiledTransform(); xslDoc.Load(@Configuration.BonusTemplate); XsltArgumentList xslArgs = new XsltArgumentList(); StringWriter writer = new StringWriter(); // Merge XSLT document with data XML document // (writer will hold resulted transformation). xslDoc.Transform(xmlDoc, xslArgs, writer); return(writer.ToString()); }
/// <summary> /// Transforms xml using specified xslt name and its parameters. /// </summary> /// <param name="xml">Input xml.</param> /// <param name="xslt">XSL Transformation.</param> /// <param name="printProfileXml">The print config.</param> /// <param name="driverConfig">The driver config.</param> /// <returns>Transformed xml.</returns> public static string TransformXml(string xml, string xslt, string printProfileXml, string driverConfig) { if (String.IsNullOrEmpty(xslt)) { string obfuscatedXml = null; //cut the xml declaration if present if (xml.StartsWith("<?", StringComparison.Ordinal)) { obfuscatedXml = xml.Substring(xml.IndexOf("?>", StringComparison.Ordinal) + 2); } else { obfuscatedXml = xml; } return(obfuscatedXml); } XDocument xsltDoc = XDocument.Parse(xslt); XDocument xmlDoc = XDocument.Parse(xml); xmlDoc.Root.Add(XElement.Parse(printProfileXml)); if (!String.IsNullOrEmpty(driverConfig)) { xmlDoc.Root.Add(XElement.Parse(driverConfig)); } StringBuilder output = new StringBuilder(); XslCompiledTransform transform = null; //Get transformation from cache or create a new one short hash = BitConverter.ToInt16(MakoPrintPdf.md5.ComputeHash(Encoding.UTF8.GetBytes(xsltDoc.ToString())), 0); lock (MakoPrintPdf.xsltCache) { if (MakoPrintPdf.xsltCache.ContainsKey(hash)) { transform = MakoPrintPdf.xsltCache[hash]; } else { using (XmlReader xsltReader = xsltDoc.CreateReader()) { transform = new XslCompiledTransform(); transform.Load(xsltReader); MakoPrintPdf.xsltCache.Add(hash, transform); } } XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.OmitXmlDeclaration = true; writerSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader xmlReader = xmlDoc.CreateReader()) using (XmlWriter writer = XmlWriter.Create(output, writerSettings)) { transform.Transform(xmlReader, null, writer); } } return(output.ToString()); }
protected void btnUpload_Click(object sender, EventArgs e) { string filepath = CommonLogic.SafeMapPath("../images") + "\\"; string filename = "priceexport_" + Localization.ToNativeDateTimeString(System.DateTime.Now).Replace(" ", "").Replace("/", "").Replace(":", "").Replace(".", ""); string fileextension = String.Empty; string xml = AppLogic.ExportProductList(Localization.ParseNativeInt(ddCategory.SelectedValue), Localization.ParseNativeInt(ddSection.SelectedValue), Localization.ParseNativeInt(ddManufacturer.SelectedValue), Localization.ParseNativeInt(ddDistributor.SelectedValue), Localization.ParseNativeInt(ddGenre.SelectedValue), Localization.ParseNativeInt(ddVector.SelectedValue)); string exporttype = rblExport.SelectedValue; //remove old export files string[] oldfiles = Directory.GetFiles(filepath, "priceexport_*." + exporttype); foreach (string oldfile in oldfiles) { try { File.Delete(oldfile); } catch { } } XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xml); string FullFilePath = filepath + filename; XslCompiledTransform xsl = new XslCompiledTransform(); Customer c = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer; XsltArgumentList args = new XsltArgumentList(); args.AddParam("locale", "", c.LocaleSetting); if (exporttype == "xls") { FullFilePath += ".xls"; fileextension = ".xls"; xsl.Load(CommonLogic.SafeMapPath("XmlPackages/ProductPricingExportExcel.xslt")); StringWriter xsw = new StringWriter(); xsl.Transform(xdoc, args, xsw); xdoc.LoadXml(xsw.ToString()); XmlToExcel.ConvertToExcel(xdoc, FullFilePath); } else { if (exporttype == "xml") { FullFilePath += ".xml"; fileextension = ".xml"; xsl.Load(CommonLogic.SafeMapPath("XmlPackages/ProductPricingExport.xslt")); } else { FullFilePath += ".csv"; fileextension = ".csv"; xsl.Load(CommonLogic.SafeMapPath("XmlPackages/ProductPricingExportCSV.xslt")); } StreamWriter sw = new StreamWriter(FullFilePath); xsl.Transform(xdoc, args, sw); sw.Close(); } Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=ProductPricing" + fileextension); Response.BufferOutput = false; if (exporttype == "xml") { //Send the XML Response.ContentType = "text/xml"; Response.Write(XmlCommon.PrettyPrintXml(CommonLogic.ReadFile(FullFilePath, false))); Response.Flush(); Response.End(); } else if (exporttype == "xls") { Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; Response.TransmitFile(FullFilePath); Response.Flush(); Response.End(); } else { // Send the CSV Response.BufferOutput = false; Response.ContentType = "application/x-unknown"; Response.TransmitFile(FullFilePath); Response.Flush(); Response.End(); } }
static void Main(string[] args) { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("../../students.xsl"); xslt.Transform("../../students.xml", "../../students.html"); }
public static void ConverXmlToHtml() { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(@"..\..\..\XML_export\test.xsl"); xslt.Transform(@"..\..\..\XML_export\test.xml", @"..\..\..\XML_export\students.html"); }
public RssTest() { _xslCompiledTransform = new XslCompiledTransform(); _xslCompiledTransform.Load(XsltFile); }
// Function : Export_with_XSLT_Windows // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek( 0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content File.WriteAllText(FileName, sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); sw.Dispose(); stream.Dispose(); } catch(Exception Ex) { throw Ex; } }
/// <summary> /// Initializes a new instance of the MvpXslTransform class. /// </summary> public MvpXslTransform() { this.compiledTransform = new XslCompiledTransform(); }
protected void BtnSaveToExcel(object sender, EventArgs e) { string json = ExcelGridData.Value.ToString(); json = json.Replace("retailid", "单据号"); json = json.Replace("setdate", "销售日期"); json = json.Replace("znums", "数量"); json = json.Replace("zxsums", "现价金额"); json = json.Replace("zssums", "结算金额"); json = json.Replace("FCalcSums", "实销金额"); json = json.Replace("yhsum", "优惠金额"); json = json.Replace("s_sums", "实收金额"); json = json.Replace("vipcode", "VIP卡号"); json = json.Replace("s_name", "营业员"); json = json.Replace("x_name", "班组"); json = json.Replace("crdate", "制单日期"); json = json.Replace("cr_name", "制单人"); json = json.Replace("comment", "备注"); StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null); XmlNode xml = eSubmit.Xml; this.Response.Clear(); this.Response.ContentType = "application/vnd.ms-excel"; this.Response.AddHeader("Content-Disposition", "attachment; filename=Retail" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); XslCompiledTransform xtExcel = new XslCompiledTransform(); xtExcel.Load(Server.MapPath("ExcelTemp/Excel.xsl")); xtExcel.Transform(xml, null, this.Response.OutputStream); this.Response.End(); }
public virtual XmlDocument GetQueryAsDOM(IDictionary <string, string> formProperties, string queryTemplateName) { XslCompiledTransform ts = compiledTemplatesCache[queryTemplateName]; return(GetQueryAsDOM(formProperties, ts)); }
public ParserTraceUITransform(string xslName) { m_transform = XmlUtils.CreateTransform(xslName, "PresentationTransforms"); }
/// <summary> /// Create a formatter structure for the given transform file /// </summary> /// <param name="transformFile">The full path to a transform file</param> public Formatter(string transformFile) { myTransformFile = transformFile; myTransform = null; }
static void Main() { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(@"../../students.xsl"); xslt.Transform(@"../../StudentSystem.xml", "../../students.html"); }
public virtual void AddDefaultQueryTemplate(Stream xslIs) { defaultCompiledTemplates = GetTemplates(xslIs); }
public XmlDocument GeneraFacturaXml(string certificado, string llave, bool incluirDetallista, bool incluirAddenda, bool incluirAlsuper, bool incluirEdifact, bool incluirComercExt, bool incluirPago, out string cadenaOriginal, out string sello) { int cantComplementos = 0; // tipoComplemento: detallista, addenda, alsuper string tipoComplemento = string.Empty; // Generamos el comprobante y agregamos el certificado GeneraComprobante(); _comprobante.Certificado = certificado; #region Agregamos el nodo detallista if (incluirDetallista) { tipoComplemento = "detallista"; ComplementoFE complemento = new ComplementoFE(_iniAdd); XmlDocument tempDocument = complemento.GeneraComplementoXml(tipoComplemento); _comprobante.Complemento = new Schemasv33.ComprobanteComplemento[1]; _comprobante.Complemento[0] = new Schemasv33.ComprobanteComplemento { Any = new[] { tempDocument["detallista:detallista"] } }; cantComplementos += 1; } #endregion #region Agrega Complemento Comercio Exterior if (incluirComercExt) { tipoComplemento = "comercExterior"; ComplementoFE complemento = new ComplementoFE(_iniAdd); XmlDocument tempDocument = complemento.GeneraComplementoXml(tipoComplemento); _comprobante.Complemento = new Schemasv33.ComprobanteComplemento[1]; _comprobante.Complemento[0] = new Schemasv33.ComprobanteComplemento { Any = new[] { tempDocument["cce11:ComercioExterior"] } }; cantComplementos += 1; } #endregion #region Agrega Complemento de Pago if (incluirPago) { tipoComplemento = "pago"; ComplementoFE complemento = new ComplementoFE(_iniAdd); XmlDocument tempDocument = complemento.GeneraComplementoXml(tipoComplemento); _comprobante.Complemento = new Schemasv33.ComprobanteComplemento[1]; _comprobante.Complemento[0] = new Schemasv33.ComprobanteComplemento { Any = new[] { tempDocument["pago10:Pagos"] } }; cantComplementos += 1; } #endregion #region Generamos un documento XML usando la información actual de comprobante, detallista y ComercExt XmlDocument doc = new XmlDocument(); using (MemoryStream tempStream = new MemoryStream()) { XmlSerializer serializer = new XmlSerializer(typeof(Schemasv33.Comprobante)); serializer.Serialize(tempStream, _comprobante); tempStream.Seek(0, SeekOrigin.Begin); doc.Load(tempStream); } #endregion #region Generamos la cadena original using (MemoryStream tempStream = new MemoryStream()) { using ( XmlTextWriter xmlWriter = new XmlTextWriter(tempStream, Encoding.UTF8)) { doc.WriteContentTo(xmlWriter); xmlWriter.Flush(); tempStream.Seek(0, SeekOrigin.Begin); XPathDocument xpathFactura = new XPathDocument(tempStream); xmlWriter.Close(); // Generamos la cadena original usando el archivo XSLT del SAT Ver33 XslCompiledTransform xslCadena = new XslCompiledTransform(); xslCadena.Load("cadenaoriginal_3_3.xslt"); using (MemoryStream cadenaStream = new MemoryStream()) { xslCadena.Transform(xpathFactura, null, cadenaStream); cadenaOriginal = cadenaStream.GetString(); } } } // Elimina saltos de linea y espacios en blanco entre los campos de la cadena original char[] crlf = new char[] { '\n', '\r' }; string[] cadenaLineas = cadenaOriginal.Split(crlf); cadenaOriginal = null; for (int i = 0; i < cadenaLineas.Length; i++) { if ((cadenaLineas[i].Length >= 2) || (cadenaLineas[i].StartsWith("-"))) { cadenaOriginal += cadenaLineas[i].Substring(2).Trim(); } } #endregion #region Generamos el sello de la factura // La encriptación de la versión 33 debe ser en SHA-256 RSACryptoServiceProvider provider = OpenSSL.GetRsaProviderFromPem(llave); if (provider == null) { throw new Exception( "No se pudo crear el proveedor de seguridad a partir del archivo fel"); } byte[] selloBytes = provider.SignData( Encoding.UTF8.GetBytes(cadenaOriginal), "SHA256"); sello = Convert.ToBase64String(selloBytes); // Actualizamos el documento original con el sello _comprobante.Sello = sello; #endregion #region Agregamos la addenda if (incluirAddenda) { tipoComplemento = "addenda"; ComplementoFE complemento = new ComplementoFE(_iniAdd); XmlDocument tempDocument = complemento.GeneraComplementoXml(tipoComplemento, cadenaOriginal); _comprobante.Addenda = new Schemasv33.ComprobanteAddenda { Any = new[] { tempDocument["Addenda"]["requestForPayment"] } }; } #endregion #region Agrega addenda Alsuper if (incluirAlsuper) { tipoComplemento = "alsuper"; ComplementoFE complemento = new ComplementoFE(_iniAdd); XmlDocument tempDocument = complemento.GeneraComplementoXml(tipoComplemento); _comprobante.Addenda = new Schemasv33.ComprobanteAddenda { Any = new[] { tempDocument["alsuper:Alsuper"] } }; } #endregion #region Agrega addenda EDIFACT if (incluirEdifact) { tipoComplemento = "edifact"; ComplementoFE complemento = new ComplementoFE(_iniAdd); XmlDocument tempDocument = complemento.GeneraComplementoXml(tipoComplemento, cadenaOriginal, sello); _comprobante.Addenda = new Schemasv33.ComprobanteAddenda { Any = new[] { tempDocument["lev1add:EDCINVOICE"] } }; } #endregion #region Genera documento final using (MemoryStream tempStream = new MemoryStream()) { doc = new XmlDocument(); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add("cfdi", "http://www.sat.gob.mx/cfd/3"); XmlSerializer serializer = new XmlSerializer(typeof(Schemasv33.Comprobante)); serializer.Serialize(tempStream, _comprobante, namespaces); tempStream.Seek(0, SeekOrigin.Begin); doc.Load(tempStream); } #endregion #region Agregar atributos finales al documento XmlAttribute xsiAttrib = doc.CreateAttribute("xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance"); string textoAtributo = "http://www.sat.gob.mx/cfd/3 " + "http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv33.xsd " + "http://www.sat.gob.mx/detallista " + "http://www.sat.gob.mx/sitio_internet/cfd/detallista/detallista.xsd"; if (incluirAlsuper) { textoAtributo = textoAtributo + " http://proveedores.alsuper.com/CFD " + "http://proveedores.alsuper.com/addenda/1.xsd"; } if (incluirComercExt) { textoAtributo = textoAtributo + " http://www.sat.gob.mx/ComercioExterior11 " + "http://www.sat.gob.mx/sitio_internet/cfd/ComercioExterior11/ComercioExterior11.xsd"; } if (incluirPago) { textoAtributo = textoAtributo + " http://www.sat.gob.mx/Pagos " + "http://www.sat.gob.mx/sitio_internet/cfd/Pagos/Pagos10.xsd"; } xsiAttrib.InnerText = textoAtributo; doc["cfdi:Comprobante"].Attributes.Append(xsiAttrib); #endregion return(doc); }
/// <summary> /// Fast means of constructing query using a precompiled stylesheet /// </summary> public static string GetQueryAsXmlString(IDictionary <string, string> formProperties, XslCompiledTransform template) { // TODO: Suppress XML header with encoding (as Strings have no encoding) using (var stream = new MemoryStream()) { TransformCriteria(formProperties, template, stream); using (StreamReader reader = new StreamReader(stream)) { return(reader.ReadToEnd()); } } }
static void Main() { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("../../catalog.xsl"); xslt.Transform("../../catalog.xml", "../../catalog.html"); }
/// <summary> /// Initializes a new instance of the MvpXslTransform /// class with the specified debug setting. /// </summary> public MvpXslTransform(bool debug) { this.compiledTransform = new XslCompiledTransform(debug); }
/// <summary> /// Generate the order receipt using XSL Transformation /// </summary> public void GenerateReceipt() { string templatePath = Server.MapPath(ZNodeConfigManager.EnvironmentConfig.ConfigPath + "Receipt.xsl"); XmlDocument xmlDoc = new XmlDocument(); XmlElement rootElement = GetElement(xmlDoc, "Order", ""); rootElement.AppendChild(GetElement(xmlDoc, "SiteName", ZNodeConfigManager.SiteConfig.CompanyName)); rootElement.AppendChild(GetElement(xmlDoc, "AccountId", _Order.AccountID.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "ReceiptText", ZNodeConfigManager.MessageConfig.GetMessage("OrderReceiptConfirmationIntroText"))); rootElement.AppendChild(GetElement(xmlDoc, "CustomerServiceEmail", ZNodeConfigManager.SiteConfig.CustomerServiceEmail)); rootElement.AppendChild(GetElement(xmlDoc, "CustomerServicePhoneNumber", ZNodeConfigManager.SiteConfig.CustomerServicePhoneNumber)); rootElement.AppendChild(GetElement(xmlDoc, "FeedBack", FeedBackUrl)); if (_Order.CardTransactionID != null) { rootElement.AppendChild(GetElement(xmlDoc, "TransactionID", _Order.CardTransactionID)); } rootElement.AppendChild(GetElement(xmlDoc, "PromotionCode", _Order.CouponCode)); rootElement.AppendChild(GetElement(xmlDoc, "PONumber", _Order.PurchaseOrderNumber)); rootElement.AppendChild(GetElement(xmlDoc, "OrderId", _Order.OrderID.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "OrderDate", _Order.OrderDate.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "ShippingName", _shoppingCart.Shipping.ShippingName)); rootElement.AppendChild(GetElement(xmlDoc, "PaymentName", _shoppingCart.Payment.PaymentName)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressCompanyName", _Order.ShippingAddress.CompanyName)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressFirstName", _Order.ShippingAddress.FirstName)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressLastName", _Order.ShippingAddress.LastName)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressStreet1", _Order.ShippingAddress.Street1)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressStreet2", _Order.ShippingAddress.Street2)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressCity", _Order.ShippingAddress.City)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressStateCode", _Order.ShippingAddress.StateCode)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressPostalCode", _Order.ShippingAddress.PostalCode)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressCountryCode", _Order.ShippingAddress.CountryCode)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressPhoneNumber", _Order.ShippingAddress.PhoneNumber)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressCompanyName", _Order.BillingAddress.CompanyName)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressFirstName", _Order.BillingAddress.FirstName)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressLastName", _Order.BillingAddress.LastName)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressStreet1", _Order.BillingAddress.Street1)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressStreet2", _Order.BillingAddress.Street2)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressCity", _Order.BillingAddress.City)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressStateCode", _Order.BillingAddress.StateCode)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressPostalCode", _Order.BillingAddress.PostalCode)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressCountryCode", _Order.BillingAddress.CountryCode)); rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressPhoneNumber", _Order.BillingAddress.PhoneNumber)); XmlElement items = xmlDoc.CreateElement("Items"); foreach (ZNodeShoppingCartItem shoppingCartItem in _shoppingCart.ShoppingCartItems) { XmlElement item = xmlDoc.CreateElement("Item"); item.AppendChild(GetElement(xmlDoc, "Quantity", shoppingCartItem.Quantity.ToString())); ZNodeGenericCollection<ZNodeDigitalAsset> assetCollection = shoppingCartItem.Product.ZNodeDigitalAssetCollection; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(shoppingCartItem.Product.Name + "<br />"); if (assetCollection.Count > 0) { sb.Append("DownloadLink : <a href='" + shoppingCartItem.Product.DownloadLink + "' target='_blank'>" + shoppingCartItem.Product.DownloadLink + "</a><br />"); foreach (ZNodeDigitalAsset digitalAsset in assetCollection) { sb.Append(digitalAsset.DigitalAsset + "<br />"); } } item.AppendChild(GetElement(xmlDoc, "Name", sb.ToString())); item.AppendChild(GetElement(xmlDoc, "SKU", shoppingCartItem.Product.SKU)); item.AppendChild(GetElement(xmlDoc, "Description", shoppingCartItem.Product.ShoppingCartDescription)); item.AppendChild(GetElement(xmlDoc, "Note", "")); item.AppendChild(GetElement(xmlDoc, "Price", shoppingCartItem.UnitPrice.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); item.AppendChild(GetElement(xmlDoc, "Extended", shoppingCartItem.ExtendedPrice.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); items.AppendChild(item); } rootElement.AppendChild(GetElement(xmlDoc, "TaxCostValue", _Order.TaxCost.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "SalesTaxValue", _Order.SalesTax.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "VATCostValue", _Order.VAT.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "HSTCostValue", _Order.HST.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "PSTCostValue", _Order.PST.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "GSTCostValue", _Order.GST.ToString())); rootElement.AppendChild(GetElement(xmlDoc, "SubTotal", _Order.SubTotal.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "TaxCost", _Order.TaxCost.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "SalesTax", _Order.SalesTax.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "VAT", _Order.VAT.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "HST", _Order.HST.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "PST", _Order.PST.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "GST", _Order.GST.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); // rootElement.AppendChild(GetElement(xmlDoc, "DiscountAmount", "-" + _Order.DiscountAmount.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "ShippingName", _shoppingCart.Shipping.ShippingName)); rootElement.AppendChild(GetElement(xmlDoc, "ShippingCost", _Order.ShippingCost.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "TotalCost", _Order.Total.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix())); rootElement.AppendChild(GetElement(xmlDoc, "AdditionalInstructions", _Order.AdditionalInstructions)); rootElement.AppendChild(items); xmlDoc.AppendChild(rootElement); // Use a memorystream to store the result into the memory MemoryStream ms = new MemoryStream(); XslCompiledTransform xsl = new XslCompiledTransform(); xsl.Load(templatePath); xsl.Transform(xmlDoc, null, ms); // Move to the begining ms.Seek(0, SeekOrigin.Begin); // Pass the memorystream to a streamreader StreamReader sr = new StreamReader(ms); _receiptTemplate = sr.ReadToEnd(); }
private string Transform(string xml, string xsl, XsltArgumentList argsList) { XDocument selectedXml = XDocument.Parse(xml); XslCompiledTransform xmlTransform = new XslCompiledTransform(); StringBuilder htmlOutput = new StringBuilder(); XmlWriter writer = XmlWriter.Create(htmlOutput); xmlTransform.Load(xsl); xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer); return htmlOutput.ToString(); }
public void renderLoginControls() { try { string XmlPath = Server.MapPath("xml/UserLogin.xml"); string XsltPath = Server.MapPath("xslt/UserLogin.xslt"); XPathDocument xdoc = new XPathDocument(XmlPath); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(XsltPath); StringWriter sw = new StringWriter(); //Transform transform.Transform(xdoc, null, sw); string result = sw.ToString(); //Remove Namespace result = result.Replace("xmlns:asp=\"remove\"", ""); result = result.Replace("xmlns:cc1=\"remove\"", ""); //Parse Control Control ctrl = Page.ParseControl(result); phLogin.Controls.Add(ctrl); } catch (Exception ex) { objNLog.Error("Error : " + ex.Message); } }
protected void ShowStyledPage() { if (Request["clear_templates"] == "1") { transformer = null; } if (Request["checkconfig"] == "1") { if (Request["config"] == null || Request["config"].Length == 0) { Response.Write("No config supplied"); } string wrappedConfig = "<newconfig>" + Request["config"] + "</newconfig>"; XmlDocument newconfig = new XmlDocument(); try { newconfig.LoadXml(wrappedConfig); } catch (Exception ex) { Response.Write(ex.Message); return; } Response.Write("Config is OK"); } else { string sourcefile = Request["source"]; string stylesheet = Server.MapPath(@"\skins\acs\HTMLOutput.xsl"); sourcefile = @"App_Data/" + sourcefile; XmlDocument source = new XmlDocument(); source.Load(Server.MapPath(sourcefile)); RewriteConfig(ref source); lock (locker) { if (transformer == null) { transformer = new XslCompiledTransform(); // this stuff is necessary to cope with our stylesheets having DTDs // Without all this settings and resolver stuff, you can't use the Load method // and tell it to allow DTDs XmlReaderSettings xset = new XmlReaderSettings(); xset.DtdProcessing = DtdProcessing.Parse; using (XmlReader xread = XmlReader.Create(stylesheet, xset)) { try { transformer.Load(xread, XsltSettings.TrustedXslt, new XmlUrlResolver()); } catch (Exception e) { throw new XsltException("Couldn't load xslt file: " + stylesheet, e); } } } } StringWriter sw = new StringWriter(); transformer.Transform(source, null, sw); string output = sw.ToString(); Response.Write(output); } }