public XmlDestination HandleResultDocument(string href, Uri baseUri) { DomDestination destination = new DomDestination(); results[href] = destination; return(destination); }
private string Transform(string stylesheetContent, string xmlPath, bool addErrorsPhase = false) { FileInfo xmlInfo = new FileInfo(xmlPath); XdmNode stylesheet = builder.Build(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(stylesheetContent)))); XsltCompiler compiler = processor.NewXsltCompiler(); XsltExecutable exec = compiler.Compile(stylesheet); XsltTransformer transformer = exec.Load(); DomDestination dest = new DomDestination(); using (var inputStream = xmlInfo.OpenRead()) { if (addErrorsPhase) { transformer.SetParameter(new QName("phase"), XdmValue.MakeValue("errors")); } transformer.SetInputStream(inputStream, new Uri(xmlInfo.DirectoryName)); transformer.Run(dest); } using (StringWriter sw = new StringWriter()) { if (dest.XmlDocument == null) { throw new Exception("Failed to execute Schematron validation. The SCH file selected may not be the ISO version of Schematron."); } dest.XmlDocument.Save(sw); return(sw.ToString()); } }
// https://www.nuget.org/packages/Saxon-HE/ public string XQuery(string xml, string query) { Processor processor = new Processor(); XmlDocument input = new XmlDocument(); input.LoadXml(xml); XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input)); DomDestination qout = new DomDestination(); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile(query); XQueryEvaluator eval = exp.Load(); eval.ContextItem = indoc; eval.Run(qout); XmlDocument outdoc = qout.XmlDocument; using (var stringWriter = new StringWriter()) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { outdoc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); return(stringWriter.GetStringBuilder().ToString()); } }
/** * Show how to transform a DOM tree into another DOM tree. * This uses the System.Xml parser to parse an XML file into a * DOM, and create an output DOM. In this Example, Saxon uses a * third-party DOM as both input and output. */ public static void ExampleDOMtoDOM(String sourceUri, String xsltUri) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document (in practice, it would already exist as a DOM) XmlDocument doc = new XmlDocument(); doc.Load(new XmlTextReader(sourceUri)); XdmNode input = processor.NewDocumentBuilder().Wrap(doc); // Create a compiler XsltCompiler compiler = processor.NewXsltCompiler(); // Compile the stylesheet XsltTransformer transformer = compiler.Compile(new Uri(xsltUri)).Load(); // Run the transformation transformer.InitialContextNode = input; DomDestination result = new DomDestination(); transformer.Run(result); // Serialize the result so we can see that it worked Console.WriteLine(result.XmlDocument.OuterXml); }
public XmlDocument Validation(string xmlfile) { XmlDocument doc = null; DomDestination dom = new DomDestination(); Stream src = null; try { if (_schematron == null) { throw new Exception("incompleted schema stylesheet"); } FileInfo file = new FileInfo(xmlfile); Uri baseuri = new Uri(file.DirectoryName + "/"); src = file.OpenRead(); _schematron.SetInputStream(src, baseuri); _schematron.Run(dom); doc = dom.XmlDocument; } catch (Exception ex) { throw ex; } finally { dom.Close(); src?.Close(); src?.Dispose(); } return(doc); }
public override bool TransformXml(string SourceXmlPath, string OutputPath) { var input = new FileInfo(SourceXmlPath); var output = new FileInfo(OutputPath); DomDestination destination = new DomDestination(); try { // Do transformation to a destination using (var inputStream = input.OpenRead()) { CompiledXform.SetInputStream(inputStream, new Uri(input.DirectoryName)); CompiledXform.Run(destination); } } catch (Exception Ex) { Console.WriteLine(Ex.ToString() + "\n" + Ex.StackTrace); return(false); } // Save result to file destination.XmlDocument.Save(output.FullName); return(true); }
private Stream Transform(XsltTransformer xslt, Stream src, Uri baseuri) { MemoryStream dst = null; DomDestination dom = new DomDestination(); try { xslt.SetInputStream(src, baseuri); xslt.Run(dom); dst = new MemoryStream(); dom.XmlDocument.Save(dst); dst.Flush(); dst.Position = 0; } catch (Exception ex) { throw ex; } finally { dom.Close(); } return(dst); }
public static string SaxonTransform(string xsltFilename, string inputXML) { var xslt = new FileInfo(xsltFilename); var input = new FileInfo(inputXML); var output = new FileInfo(@"test.html"); // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(xslt.FullName)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } // Save result to a file (or whatever else you wanna do) // destination.XmlDocument.Save(output.FullName); return(destination.XmlDocument.OuterXml); }
private static string Transform(string html) { var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Trifolia.Shared.htmlToOpenXml.xsl")); var dest = new DomDestination(); using (MemoryStream ms = new MemoryStream(ASCIIEncoding.UTF8.GetBytes("<root>" + html + "</root>"))) { var transformer = executable.Load(); // Parameters to stylesheet transformer.SetParameter(new QName("linkStyle"), new XdmAtomicValue(Properties.Resource.LinkStyle)); transformer.SetParameter(new QName("bulletListStyle"), new XdmAtomicValue("ListBullet")); transformer.SetParameter(new QName("orderedListStyle"), new XdmAtomicValue("ListNumber")); transformer.SetInputStream(ms, new Uri("https://trifolia.lantanagroup.com/")); transformer.Run(dest); } using (MemoryStream ms = new MemoryStream()) { dest.XmlDocument.Save(ms); return(ASCIIEncoding.UTF8.GetString(ms.ToArray())); } }
public string Run(string path, bool isContingencia) { try { string assembly = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Log.Info(string.Format("Caminho para gerar o arquivo 'NFCePrt.html' para o WebBVrowser: {0}", assembly)); if (assembly != null) { // string nfcePath = assembly.ToLower().Replace("\\bin\\debug", "\\nfce"); string nfcePath = BmsSoftware.ConfigSistema1.Default.PathInstall; /* algum erro no parser para executar a identificação de nfce normal ou contingencia... criado outro arquivo para nao perder tempo neste exemplo */ string xsltInput = String.Concat(nfcePath, isContingencia ? "\\xsl\\NFCeContingencia.xsl" : "\\xsl\\NFCe.xsl"); Log.Debug(String.Format("xsltInput: [{0}]", xsltInput)); /* criado um html de exemplo...*/ string xsltOutput = String.Concat(nfcePath, "\\NFCePrt.html"); Log.Debug(String.Format("xsltOutput: [{0}]", xsltOutput)); var xslt = new FileInfo(xsltInput); var input = new FileInfo(path); var output = new FileInfo(xsltOutput); Log.Debug(String.Format("input File XML: [{0}]", input)); // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(xslt.FullName)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); if (input.DirectoryName != null) { transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); } transformer.Run(destination); } destination.XmlDocument.Save(output.FullName); return(destination.XmlDocument.OuterXml); } else { return(null); } } catch (Exception e) { MessageBox.Show(String.Format("Erro na geração do xslt. Erro:{0} Message: {1}", e.Message, e.InnerException), @"Gerar XSLT", MessageBoxButtons.OK, MessageBoxIcon.Error); Log.Debug("ERROR MESSAGE: " + e.Message); Log.Debug("ERROR INNERMESSAGE: " + e.InnerException); return(null); } }
/** * Show how to run two queries in tandem. The second query is applied to the * results of the first. */ public static void ExampleExtra() { // place-holder to add user-defined examples for testing Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile(@"<out>{matches('ABC', '\p{IsBasicLatin}*')}</out>"); XQueryEvaluator eval = exp.Load(); DomDestination dest = new DomDestination(); eval.Run(dest); Console.WriteLine(dest.XmlDocument.OuterXml); }
/// <summary> /// Xslt Version 2.0 Transformation /// </summary> public void TransformXmlV2(string xmlContent, string xsltPath, string outputPath) { /* * var xml = new XmlDocument(); * xml.LoadXml(xmlContent); * var dest = new TextWriterDestination(XmlWriter.Create(outputPath)); * var processor = new Processor(); * var xr = XmlReader.Create(xsltPath); * * try { * var transformer = processor.NewXsltCompiler().Compile(xr).Load(); * transformer.InitialContextNode = processor.NewDocumentBuilder().Build(xml); * transformer.Run(dest); * } * finally { * try { * xr.Close(); * dest.Close(); * } * catch { } * } */ Random r = new Random(); int rInt = r.Next(0, 100); var tempFile = @"c:\windows\temp\xt_" + new DateTime().ToString("yyyyMMddHHmmss") + rInt; File.WriteAllText(tempFile, xmlContent, Encoding.UTF8); var input = new FileInfo(tempFile); var xslt = new FileInfo(xsltPath); var output = new FileInfo(outputPath); var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(xslt.FullName)); var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } destination.XmlDocument.Save(output.FullName); if (File.Exists(tempFile)) { File.Delete(tempFile); } }
/// <summary> /// Perform XQuery <paramref name="query"/> on XML document at <paramref name="input"/> using Saxon API. /// </summary> /// <param name="input">A valid XML document.</param> /// <param name="query">An XQuery query.</param> /// <returns>Returns the results of the <paramref name="query"/> as an XmlDocument.</returns> public static XmlDocument PerformQuery(XmlDocument input, string query) { var processor = new Processor(); XdmNode inputXml = processor.NewDocumentBuilder().Build(new XmlNodeReader(input)); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable executable = compiler.Compile(query); XQueryEvaluator evaluator = executable.Load(); evaluator.ContextItem = inputXml; var domOut = new DomDestination(); evaluator.Run(domOut); return(domOut.XmlDocument); }
public XmlDocument Evaluate(XmlNode node) { var nodeReader = new XmlNodeReader(node); var documentBuilder = this.processor.NewDocumentBuilder(); var document = documentBuilder.Build(nodeReader); this.evaluator.ContextItem = document; var destination = new DomDestination(); this.evaluator.Run(destination); return(destination.XmlDocument); }
public XmlDocument Run(XNode xDocument, string baseOutputUri = null, params KeyValuePair <string, object>[] arguments) { // Load the source document from an XMLReader. var reader = xDocument.CreateReader(); // Load execuable. var transformer = _executable.Load(); // Set the root node of the source document to be the initial context node transformer.InitialContextNode = _builder.Build(reader); // Set where to output xsl:result-document constructs. if (baseOutputUri != null) { transformer.BaseOutputUri = new Uri(baseOutputUri); } // Set parameters. this.SetParams(ref transformer, arguments); // The transformation destination variable. var destination = new DomDestination(); // Errors will be reported by the exception handling. transformer.Implementation.setErrorListener(new TransformerErrorListener()); // Output the transform to the above variable. var listener = new DynamicErrorListener(); try { transformer.Implementation.setErrorListener(listener); transformer.Run(destination); } catch (DynamicError) { this.ReportCompilerErrors(listener); } // Clear any set parameters. transformer.Reset(); return(destination.XmlDocument); }
private void reportButton_Click(object sender, RoutedEventArgs e) { string line = null; string line_to_delete = "<albumchart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.example.org/types\">"; using (StreamReader reader = new StreamReader(@"..\..\albumchart.xml")) { using (StreamWriter writer = new StreamWriter(@"..\..\albumchartToReport.xml")) { while ((line = reader.ReadLine()) != null) { if (String.Compare(line, line_to_delete) == 0) { writer.WriteLine("<albumchart>"); } else { writer.WriteLine(line); } } } } var xslt = new FileInfo(@"..\..\toxml.xsl"); var input = new FileInfo(@"..\..\albumchartToReport.xml"); var output = new FileInfo(@"..\..\report.xml"); var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(xslt.FullName)); var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } // Save result to a file (or whatever else you wanna do) destination.XmlDocument.Save(output.FullName); }
/** * Show a query taking a DOM as its input and producing a DOM as its output. */ public static void ExampleToDOM(String inputFileName) { Processor processor = new Processor(); XmlDocument input = new XmlDocument(); input.Load(inputFileName); XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input)); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>"); XQueryEvaluator eval = exp.Load(); eval.ContextItem = indoc; DomDestination qout = new DomDestination(); eval.Run(qout); XmlDocument outdoc = qout.XmlDocument; Console.WriteLine(outdoc.OuterXml); }
private void xhtmlButton_Click(object sender, RoutedEventArgs e) { var xslt = new FileInfo(@"..\..\toxhtml.xsl"); var input = new FileInfo(@"..\..\report.xml"); var output = new FileInfo(@"..\..\report.xhtml"); var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(xslt.FullName)); var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } // Save result to a file (or whatever else you wanna do) destination.XmlDocument.Save(output.FullName); }
public XmlDocument DoTransform() { var processor = new Processor(); var input = processor.NewDocumentBuilder().Wrap(_docToTransform); // Create a compiler var compiler = processor.NewXsltCompiler(); var builder = processor.NewDocumentBuilder(); var xsltSheetNode = builder.Build(_xsltDocReader); // Compile the stylesheet var transformer = compiler.Compile(xsltSheetNode).Load(); // Run the transformation transformer.InitialContextNode = input; var result = new DomDestination(); transformer.Run(result); return(result.XmlDocument); }
/** * Show a transformation using a user-written result document handler. This example * captures each of the result documents in a DOM, and creates a Hashtable that indexes * the DOM trees according to their absolute URI. On completion, it writes all the DOMs * to the standard output. */ public static void ExampleUsingResultDocumentHandler(String sourceUri, String xsltUri) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri)); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load(); // Set the root node of the source document to be the initial context node transformer.InitialContextNode = input; // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); // Establish the result document handler Hashtable results = new Hashtable(); transformer.ResultDocumentHandler = new ExampleResultDocumentHandler(results); // Transform the source XML to System.out. transformer.Run(serializer); // Process the captured DOM results foreach (DictionaryEntry entry in results) { string uri = (string)entry.Key; Console.WriteLine("\nResult File " + uri); DomDestination dom = (DomDestination)results[uri]; Console.Write(dom.XmlDocument.OuterXml); } }
public void SaveToDisk(XDocument xDocument, string outputDirectory) { // PRE-PROCESS // The transformation destination variable. var destinationPreprocess = new DomDestination(); // Load the source document from an XMLReader. var reader = xDocument.CreateReader(); // Set the root node of the source document to be the initial context node _transformerPreprocess.InitialContextNode = _builder.Build(reader); // BaseOutputUri is only necessary for xsl:result-document. _transformerPreprocess.BaseOutputUri = new Uri(Path.GetFullPath(outputDirectory)); // Output the transform to the above variable. _transformerPreprocess.Run(destinationPreprocess); // OUTPUT MAIN // The transformation destination variable. var destination = new DomDestination(); // Set the root node of the source document to be the initial context node _transformer.InitialContextNode = _builder.Build(destinationPreprocess.XmlDocument); // BaseOutputUri is only necessary for xsl:result-document. _transformer.BaseOutputUri = new Uri(Path.GetFullPath(outputDirectory)); // Pass the output directory to the stylesheet. this.SetParameter("workingDirectory", _transformerPreprocess.BaseOutputUri.AbsolutePath); // Output the transform to the above variable. _transformer.Run(destination); }
/// <summary> Use the Saxon-HE library to transform a source XML file with the XSLT file and return the string </summary> /// <param name="SourceFile"> Source XML file, to be transformed </param> /// <param name="XSLT_File"> XSLT file to perform the transform </param> /// <returns> XSLT return arguments including a flag for success, and possibly an exception </returns> public static XSLT_Transformer_ReturnArgs Saxon_Transform(string SourceFile, string XSLT_File) { // Keep track of the start time DateTime starTime = DateTime.Now; // Create the return object XSLT_Transformer_ReturnArgs returnArgs = new XSLT_Transformer_ReturnArgs(); returnArgs.Engine = XSLT_Transformer_Engine_Enum.Saxon; // Ensure the XSLT file exists if (!File.Exists(XSLT_File)) { returnArgs.Successful = false; returnArgs.ErrorMessage = "Indicated XSLT file ( " + XSLT_File + " ) does not exist."; return(returnArgs); } // Ensure the source file exists if (!File.Exists(SourceFile)) { returnArgs.Successful = false; returnArgs.ErrorMessage = "Indicated source file ( " + SourceFile + " ) does not exist."; return(returnArgs); } FileInfo input = new FileInfo(SourceFile); try { // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(XSLT_File)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } // Save result to a file (or whatever else you wanna do) using (var stringWriter = new StringWriter()) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { destination.XmlDocument.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); returnArgs.TransformedString = stringWriter.GetStringBuilder().ToString(); } returnArgs.Successful = true; } catch (Exception ee) { returnArgs.Successful = false; returnArgs.ErrorMessage = ee.Message; returnArgs.InnerException = ee; } // Determine the elapsed time, in milliseconds returnArgs.Milliseconds = DateTime.Now.Subtract(starTime).TotalMilliseconds; return(returnArgs); }
private void button2_Click(object sender, EventArgs e) { if (txtXSLT.Text == "") { MessageBox.Show("Надо задать путь к XSLT файлу"); return; } if (txtXML.Text == "") { MessageBox.Show("Надо задать путь к XML файлу"); return; } this.UseWaitCursor = true; Cursor.Current = Cursors.WaitCursor; xb = new XMLBuilder(); FileInfo fi = new FileInfo(txtXML.Text); string OutputFolder = fi.DirectoryName; if (Properties.Settings.Default.OutputFolder != "") { if (Directory.Exists(Properties.Settings.Default.OutputFolder)) { OutputFolder = Properties.Settings.Default.OutputFolder; } } string xmlPath = txtXML.Text; string Name = fi.Name.Replace(fi.Extension, ""); string htmlPath = OutputFolder + "\\" + Name + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".html"; string errPath = OutputFolder + "\\" + Name + "_ERROR_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"; var input = new FileInfo(xmlPath); var output = new FileInfo(htmlPath); try { // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(txtXSLT.Text)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } destination.XmlDocument.Save(output.FullName); CheckHTML(output.FullName, errPath); } catch (System.Exception ex) { txtError.Text = ex.Message; } this.UseWaitCursor = false; Cursor.Current = Cursors.Default; }
private void button3_Click(object sender, EventArgs e) { if (txtXSLT.Text == "") { MessageBox.Show("Надо задать путь к XSLT файлу"); return; } if (txtMap.Text == "") { MessageBox.Show("Надо задать путь к файлу настроек"); return; } this.UseWaitCursor = true; Cursor.Current = Cursors.WaitCursor; xb = new XMLBuilder(); FileInfo fi = new FileInfo(txtMap.Text); string OutputFolder = fi.DirectoryName; if (Properties.Settings.Default.OutputFolder != "") { if (Directory.Exists(Properties.Settings.Default.OutputFolder)) { OutputFolder = Properties.Settings.Default.OutputFolder; } } xb.OutFolder = OutputFolder; using (var stream = System.IO.File.OpenRead(txtMap.Text)) { var serializer = new XmlSerializer(typeof(xsdItem)); xb.root = serializer.Deserialize(stream) as xsdItem; } xb.root.RestoreParent(); string xmlPath = xb.BuildXML(xb.root, txtGenPaths.Text.Trim()); txtGen2.Text = xmlPath; string htmlPath = OutputFolder + "\\" + xb.root.Name + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".html"; string errPath = OutputFolder + "\\" + xb.root.Name + "_ERROR_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"; var input = new FileInfo(xmlPath); var output = new FileInfo(htmlPath); try { // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(txtXSLT.Text)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.FullName)); transformer.Run(destination); } destination.XmlDocument.Save(output.FullName); CheckHTML(output.FullName, errPath); } catch (Saxon.Api.DynamicError sad) { //txtError.Text = ex.Message + "(" + ex.LineNumber.ToString() + ")"; txtError.Text = sad.Message + "(" + sad.LineNumber + ")"; } catch (System.Exception ex) { txtError.Text = ex.Message; } this.UseWaitCursor = false; Cursor.Current = Cursors.Default; }
private void cmdRun_Click(object sender, EventArgs e) { if (txtXSLT.Text == "") { MessageBox.Show("Надо задать путь к XSLT файлу"); return; } if (txtXSD.Text == "") { MessageBox.Show("Надо задать путь к XSD файлу"); return; } this.UseWaitCursor = true; Cursor.Current = Cursors.WaitCursor; xb = new XMLBuilder(); FileInfo fi = new FileInfo(txtXSD.Text); string OutputFolder = fi.DirectoryName; if (Properties.Settings.Default.OutputFolder != "") { if (Directory.Exists(Properties.Settings.Default.OutputFolder)) { OutputFolder = Properties.Settings.Default.OutputFolder; } } xb.XSDPath = txtXSD.Text; xb.OutFolder = OutputFolder; List <string> genpaths = new List <string>(); String sPaths = ""; if (tvPath.Nodes.Count > 0) { foreach (TreeNode n in tvPath.Nodes) { if (n.Checked) { if (!genpaths.Contains((String)(n.Tag))) { genpaths.Add((String)(n.Tag)); } CollectChildPath(genpaths, n); } } foreach (string s in genpaths) { sPaths += (s + "\r"); } } else { sPaths = txtGenPaths.Text.Trim(); } System.Diagnostics.Debug.Print(sPaths); string xmlPath = xb.BuildXML(sPaths); txtGen1.Text = xmlPath; string htmlPath = OutputFolder + "\\" + xb.root.Name + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".html"; string errPath = OutputFolder + "\\" + xb.root.Name + "_ERROR_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"; var input = new FileInfo(xmlPath); var output = new FileInfo(htmlPath); try { // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(txtXSLT.Text)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.FullName)); transformer.Run(destination); } destination.XmlDocument.Save(output.FullName); CheckHTML(output.FullName, errPath); } catch (System.Exception ex) { txtError.Text = ex.Message; } this.UseWaitCursor = false; Cursor.Current = Cursors.Default; }
public static string ImportSchematron(string baseDir, string schemaPath, string xsltPath) { // Builds a new XSLT file from a schematron file. // This only needs to be done when the schematron file changes. var sxnProc = new Processor(); var outPath = xsltPath; var baseXsltPath = Path.Combine(baseDir, @"Content\Saxon\"); var schConverter = new string[] { baseXsltPath + "iso_dsdl_include.xsl", baseXsltPath + "iso_abstract_expand.xsl", baseXsltPath + "iso_svrl_for_xslt2.xsl" }; var schemaUri = new Uri(schemaPath); var xslComp = sxnProc.NewXsltCompiler(); //////transform-1///// var xslUri = new Uri(schConverter[0]); var xslExec = xslComp.Compile(xslUri); var xslTrans = xslExec.Load(); var domOut1 = new DomDestination(new XmlDocument()); using (var fs = File.Open(schemaPath, FileMode.Open, FileAccess.Read)) { xslTrans.SetInputStream(fs, schemaUri); // set baseUri xslTrans.Run(domOut1); } //////transform-2///// xslUri = new Uri(schConverter[1]); xslExec = xslComp.Compile(xslUri); xslTrans = xslExec.Load(); var domOut2 = new DomDestination(new XmlDocument()); var docBuilder = sxnProc.NewDocumentBuilder(); docBuilder.BaseUri = schemaUri; var inputDoc2 = docBuilder.Wrap(domOut1.XmlDocument); xslTrans.InitialContextNode = inputDoc2; xslTrans.Run(domOut2); //////transform-3///// xslUri = new Uri(schConverter[2]); xslExec = xslComp.Compile(xslUri); xslTrans = xslExec.Load(); var inputDoc3 = docBuilder.Wrap(domOut2.XmlDocument); xslTrans.InitialContextNode = inputDoc3; var serializer = new Serializer(); using (TextWriter tw = new StreamWriter(outPath, false)) { serializer.SetOutputWriter(tw); serializer.SetOutputProperty(Serializer.INDENT, "no"); xslTrans.Run(serializer); } return(outPath); }
public override TaskStatus Run() { Info("Transforming files..."); bool success = true; bool atLeastOneSucceed = false; foreach (FileInf file in SelectFiles()) { var destPath = Path.Combine(Workflow.WorkflowTempFolder, string.Format(OutputFormat, Path.GetFileNameWithoutExtension(file.FileName), DateTime.Now, Extension)); try { Version = XDocument.Load(XsltPath).Root.Attribute("version").Value; switch (Version) { case "1.0": var xslt = new XslCompiledTransform(); xslt.Load(XsltPath); xslt.Transform(file.Path, destPath); InfoFormat("File transformed (XSLT 1.0): {0} -> {1}", file.Path, destPath); Files.Add(new FileInf(destPath, Id)); break; case "2.0": var xsl = new FileInfo(XsltPath); var input = new FileInfo(file.Path); var output = new FileInfo(destPath); // Compile stylesheet var processor = new Processor(); var compiler = processor.NewXsltCompiler(); var executable = compiler.Compile(new Uri(xsl.FullName)); // Do transformation to a destination var destination = new DomDestination(); using (var inputStream = input.OpenRead()) { var transformer = executable.Load(); transformer.SetInputStream(inputStream, new Uri(input.DirectoryName)); transformer.Run(destination); } // Save result to a file (or whatever else you wanna do) destination.XmlDocument.Save(output.FullName); InfoFormat("File transformed (XSLT 2.0): {0} -> {1}", file.Path, destPath); Files.Add(new FileInf(destPath, Id)); break; case "3.0": var xsl3 = new FileInfo(XsltPath); var input3 = new FileInfo(file.Path); var output3 = new FileInfo(destPath); var processor3 = new Processor(false); var compiler3 = processor3.NewXsltCompiler(); var stylesheet = compiler3.Compile(new Uri(xsl3.FullName)); var serializer = processor3.NewSerializer(); serializer.SetOutputFile(output3.FullName); using (var inputStream = input3.OpenRead()) { var transformer3 = stylesheet.Load30(); transformer3.Transform(inputStream, serializer); serializer.Close(); } InfoFormat("File transformed (XSLT 3.0): {0} -> {1}", file.Path, destPath); Files.Add(new FileInf(destPath, Id)); break; default: Error("Error in version option. Available options: 1.0, 2.0 or 3.0"); return(new TaskStatus(Status.Error, false)); } // Set renameTo and tags from /*//<WexflowProcessing>//<File> nodes // Remove /*//<WexflowProcessing> nodes if necessary var xdoc = XDocument.Load(destPath); var xWexflowProcessings = xdoc.Descendants("WexflowProcessing").ToArray(); foreach (var xWexflowProcessing in xWexflowProcessings) { var xFiles = xWexflowProcessing.Descendants("File"); foreach (var xFile in xFiles) { try { var taskId = int.Parse(xFile.Attribute("taskId").Value); string fileName = xFile.Attribute("name").Value; var xRenameTo = xFile.Attribute("renameTo"); string renameTo = xRenameTo != null ? xRenameTo.Value : string.Empty; var tags = (from xTag in xFile.Attributes() where xTag.Name != "taskId" && xTag.Name != "name" && xTag.Name != "renameTo" && xTag.Name != "path" && xTag.Name != "renameToOrName" select new Tag(xTag.Name.ToString(), xTag.Value)).ToList(); var fileToEdit = (from f in Workflow.FilesPerTask[taskId] where f.FileName.Equals(fileName) select f).FirstOrDefault(); if (fileToEdit != null) { fileToEdit.RenameTo = renameTo; fileToEdit.Tags.AddRange(tags); InfoFormat("File edited: {0}", fileToEdit.ToString()); } else { ErrorFormat("Cannot find the File: {{fileName: {0}, taskId:{1}}}", fileName, taskId); } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while editing the file: {0}. Error: {1}", xFile.ToString(), e.Message); } } } if (RemoveWexflowProcessingNodes) { xWexflowProcessings.Remove(); xdoc.Save(destPath); } if (!atLeastOneSucceed) { atLeastOneSucceed = true; } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while transforming the file {0}", e, file.Path); success = false; } } var status = Status.Success; if (!success && atLeastOneSucceed) { status = Status.Warning; } else if (!success) { status = Status.Error; } Info("Task finished."); return(new TaskStatus(status, false)); }