public static string TransformSAXON(string documentPath, string xsltPath, bool schemaAware) { Processor processor = new Processor(); XsltCompiler xsltCompiler = processor.NewXsltCompiler(); xsltCompiler.Processor.SetProperty(FeatureKeys.GENERATE_BYTE_CODE, "false"); XsltExecutable xsltExecutable = xsltCompiler.Compile(new Uri("file://" + xsltPath)); XsltTransformer xsltTransformer = xsltExecutable.Load(); if (schemaAware //!string.IsNullOrEmpty(xsdPath) ) { xsltTransformer.SchemaValidationMode = SchemaValidationMode.Strict; } using (FileStream fileStream = File.OpenRead(documentPath)) { xsltTransformer.SetInputStream(fileStream, new Uri(@"file://" + documentPath)); XdmDestination destination = new XdmDestination(); xsltTransformer.Run(destination); StringBuilder outputBuilder = new StringBuilder(); outputBuilder.Append(destination.XdmNode.OuterXml); return(outputBuilder.ToString()); } }
private bool compareXML(String actual, String gold) { try { if (xmlComparer == null) { xmlComparer = processor.NewXsltCompiler().Compile(new Uri(testSuiteDir + "/SaxonResults.net/compare.xsl")); } XdmNode doc1 = processor.NewDocumentBuilder().Build(new Uri(actual)); XdmNode doc2 = processor.NewDocumentBuilder().Build(new Uri(gold)); XsltTransformer t = xmlComparer.Load(); t.InitialTemplate = new QName("", "compare"); t.SetParameter(new QName("", "actual"), doc1); t.SetParameter(new QName("", "gold"), doc2); StringWriter sw = new StringWriter(); Serializer sr = new Serializer(); sr.SetOutputWriter(sw); t.Run(sr); String result = sw.ToString(); return(result.StartsWith("true")); } catch (Exception e) { Console.WriteLine("***" + e.Message); return(false); } }
///<summary> ///Performs a Saxon transformation. /// </summary> /// public override Stream Transform(Stream source, Stream xsl) { MemoryStream result = new MemoryStream(); Uri uri = new Uri("file://C:/"); //set XSLT stylesheet Processor p = new Processor(); XsltCompiler c = p.NewXsltCompiler(); c.BaseUri = uri; XsltExecutable e = c.Compile(xsl); XsltTransformer t = e.Load(); //set output var destination = new Serializer(); destination.SetOutputStream(result); t.SetInputStream(source, uri); t.Run(destination); result.Position = 0; result.Flush(); return(result); }
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 void Load(string xslPath, Dictionary <string, string> paramCollection) { try { TextReader input = new StreamReader(xslPath); var directory = new FileInfo(xslPath).Directory; if (directory != null) { compiler.BaseUri = new Uri(directory.FullName + "\\"); } transformer = compiler.Compile(input).Load(); // Set the parameters, if any were passed if (paramCollection != null) { foreach (var param in paramCollection) { transformer.SetParameter(new QName("", "", param.Key), new XdmAtomicValue(param.Value)); } } input.Close(); } catch (Exception ex) { Log.Error(ex.Message); throw; } }
/** * This shows how to set a parameter for use by the stylesheet. Use * two transformers to show that different parameters may be set * on different transformers. */ public static void ExampleParam(String sourceUri, String xsltUri) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri)); // Compile the stylesheet XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(xsltUri)); // Create two transformers with different parameters XsltTransformer transformer1 = exec.Load(); XsltTransformer transformer2 = exec.Load(); transformer1.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!")); transformer2.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("goodbye to you!")); // Now run them both transformer1.InitialContextNode = input; XdmDestination results1 = new XdmDestination(); transformer1.Run(results1); transformer2.InitialContextNode = input; XdmDestination results2 = new XdmDestination(); transformer2.Run(results2); Console.WriteLine("1: " + results1.XdmNode.StringValue); Console.WriteLine("2: " + results2.XdmNode.StringValue); }
/** * Show how to transform a tree starting at a node other than the root. */ public static void ExampleSaxonToSaxonNonRoot(String sourceUri, String xsltUri) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri)); // Navigate to the first grandchild XPathSelector eval = processor.NewXPathCompiler().Compile("/*/*[1]").Load(); eval.ContextItem = input; input = (XdmNode)eval.EvaluateSingle(); // Create an XSLT compiler XsltCompiler compiler = processor.NewXsltCompiler(); // Compile the stylesheet XsltTransformer transformer = compiler.Compile(new Uri(xsltUri)).Load(); // Run the transformation transformer.InitialContextNode = input; XdmDestination result = new XdmDestination(); transformer.Run(result); // Serialize the result so we can see that it worked Console.WriteLine(result.XdmNode.OuterXml); }
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()); } }
/** * Show the that a transformer can be reused, and show resetting * a parameter on the transformer. */ public static void ExampleTransformerReuse(String sourceUri, String xsltUri) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri)); // Compile the stylesheet XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(xsltUri)); // Create a transformer XsltTransformer transformer = exec.Load(); // Run it once transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!")); transformer.InitialContextNode = input; XdmDestination results = new XdmDestination(); transformer.Run(results); Console.WriteLine("1: " + results.XdmNode.StringValue); // Run it again transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to me!")); transformer.InitialContextNode = input; results.Reset(); transformer.Run(results); Console.WriteLine("2: " + results.XdmNode.StringValue); }
private void SetParams(ref XsltTransformer transformer, KeyValuePair <string, object>[] arguments) { foreach (var arg in arguments) { var xmlArg = arg.Value as XmlReader; if (xmlArg != null) { transformer.SetParameter(new QName(arg.Key), _builder.Build(xmlArg)); continue; } if (arg.Value is int) { transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue((int)arg.Value)); continue; } var sArg = arg.Value as string; if (sArg != null) { transformer.SetParameter(new QName(arg.Key), new XdmAtomicValue(sArg)); continue; } // If we get here then the parameter is unrecognized, so let the developer know. throw new NotImplementedException($"In {nameof(arguments)}, the conversion for the type '{arg.Value.GetType().Name}' of the value from '{arg.Key}' has not yet been implemented."); } }
/** * Show a transformation using a user-written URI Resolver. */ public static void ExampleUsingURIResolver(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; // Set the user-written XmlResolver transformer.InputXmlResolver = new UserXmlResolver(); // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); // Transform the source XML to System.out. transformer.Run(serializer); }
private String compareDocs(XdmNode doc1, XdmNode doc2) { try { XsltTransformer t = xmlComparer.Load(); t.InitialTemplate = new QName("", "compare"); t.SetParameter(new QName("", "actual"), doc1); t.SetParameter(new QName("", "gold"), doc2); t.SetParameter(new QName("", "debug"), new XdmAtomicValue(debug)); StringWriter sw = new StringWriter(); Serializer sr = new Serializer(); sr.SetOutputWriter(sw); t.Run(sr); String result = sw.ToString(); if (result.StartsWith("true")) { return("OK"); } else { return("XML comparison - not equal"); } } catch (Exception e) { Console.WriteLine("***" + e.Message); return("XML comparison failure: " + e.Message); } }
protected override void Render(TextWriter outputFileName, bool withChildren) { XmlWriterSettings outputSettings = (this.UseOutputSettings) ? XsltTransformer.XslCompiledTransform.OutputSettings.Clone() : new XmlWriterSettings { Indent = true, Encoding = GetEncoding(), OmitXmlDeclaration = this.OmitXmlDeclaration }; outputSettings.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), this.ConformanceLevel); using (XmlWriter writer = XmlWriter.Create(outputFileName, outputSettings)) { Content content = this.ContextNode; //using (Stream response = content.GetXmlStream(withChildren, this.ChildrenSetting == "AllChildren")) content.ChildrenDefinition.AllChildren = this.ChildrenSetting == "AllChildren"; content.ChildrenDefinition.ContentQuery = this.CustomQueryFilter; using (Stream response = content.GetXml(withChildren)) { var xml = new XPathDocument(response); var xsltArguments = GetXsltArgumentList(); XsltTransformer.Transform(xml, xsltArguments, writer); } } }
private string ProcessXslt(string result, string xslt) { XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(result)); string cleanXmlDocument = xmlDocumentWithoutNs.ToString(); XsltExecutable xsltExecutable = GetXsltExecutable(xslt); byte[] xmlByteArray = System.Text.Encoding.UTF8.GetBytes(cleanXmlDocument); var inputStream = new MemoryStream(xmlByteArray); XsltTransformer transformer = xsltExecutable.Load(); // Saxon requires to set an Uri for the stream; otherwise setting the input stream fails transformer.SetInputStream(inputStream, new Uri("http://localhost")); // run the transformation and save the result to string Serializer serializer = new Processor().NewSerializer(); using (var memoryStream = new MemoryStream()) { serializer.SetOutputStream(memoryStream); transformer.Run(serializer); memoryStream.Position = 0; using (var streamReader = new StreamReader(memoryStream)) { result = streamReader.ReadToEnd(); } } return(result.Contains(NoMatchString) ? null : result); }
public void Compile(FileInfo file) { Stream src = null; Stream dst = null; try { if (_processor == null) { throw new Exception("incompleted initialize"); } Uri baseuri = new Uri(file.DirectoryName + "/"); src = file.OpenRead(); dst = Transform(_iso_dsdl_include, src, baseuri); dst = Transform(_iso_abstract_expand, dst, baseuri); dst = Transform(_iso_svrl_for_xslt2, dst, baseuri); _schematron = CreateTramsformer(dst, baseuri); } catch (Exception ex) { throw new Exception($"{ex.Message}"); } finally { src?.Close(); src?.Dispose(); } }
/** * 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); }
/** * Show how to transform a Saxon tree into another Saxon tree. */ public static void ExampleSaxonToSaxon(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 compiler XsltCompiler compiler = processor.NewXsltCompiler(); // Compile the stylesheet XsltTransformer transformer = compiler.Compile(new Uri(xsltUri)).Load(); // Run the transformation transformer.InitialContextNode = input; XdmDestination result = new XdmDestination(); transformer.Run(result); // Serialize the result so we can see that it worked StringWriter sw = new StringWriter(); result.XdmNode.WriteTo(new XmlTextWriter(sw)); Console.WriteLine(sw.ToString()); // Note: we don't do // result.XdmNode.WriteTo(new XmlTextWriter(Console.Out)); // because that results in the Console.out stream being closed, // with subsequent attempts to write to it being rejected. }
public static void SimpleTransformation(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; // Set a parameter to the transformation transformer.SetParameter(new QName("", "", "greeting"), new XdmAtomicValue("hello")); // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); serializer.SetOutputProperty(Serializer.INDENT, "yes"); // Transform the source XML to Console.Out transformer.Run(serializer); }
/** * Example demonstrating call of an extension function */ public static void ExampleExtensibility(String sourceUri) { // Create a Processor instance. Processor processor = new Processor(); // Identify the Processor version Console.WriteLine(processor.ProductVersion); // Set diagnostics processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", true); // Create the stylesheet String s = @"<out xsl:version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=SampleExtensions' " + @" addition='{ext:add(2,2)}' " + @" average='{ext:average((1,2,3,4,5,6))}'/>"; // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri)); // 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); // Transform the source XML to System.out. transformer.Run(serializer); }
/** * Perform a transformation using a compiled stylesheet (a Templates object) */ public static void ExampleUseTemplatesObj( String sourceUri1, String sourceUri2, String xsltUri) { // Create a Processor instance. Processor processor = new Processor(); // Create a compiled stylesheet XsltExecutable templates = processor.NewXsltCompiler().Compile(new Uri(xsltUri)); // Note: we could actually use the same XSltTransformer in this case. // But in principle, the two transformations could be done in parallel in separate threads. // Do the first transformation Console.WriteLine("\n\n----- transform of " + sourceUri1 + " -----"); XsltTransformer transformer1 = templates.Load(); transformer1.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(sourceUri1)); transformer1.Run(new Serializer()); // default destination is Console.Out // Do the second transformation Console.WriteLine("\n\n----- transform of " + sourceUri2 + " -----"); XsltTransformer transformer2 = templates.Load(); transformer2.InitialContextNode = processor.NewDocumentBuilder().Build(new Uri(sourceUri2)); transformer2.Run(new Serializer()); // default destination is Console.Out }
/** * Show a transformation using a DTD-based validation and the id() function. */ public static void ExampleUsingDTD(String sourceUri, String xsltUri) { // Create a Processor instance Processor processor = new Processor(); // Load the source document DocumentBuilder db = processor.NewDocumentBuilder(); db.DtdValidation = true; XdmNode input = db.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; //Set the destination XdmDestination results = new XdmDestination(); // Create a serializer //Serializer results = new Serializer(); //results.SetOutputWriter(Console.Out); // Transform the XML transformer.Run(results); Console.WriteLine(results.XdmNode.ToString()); }
public void TestSaxonFromFileToStream()//string sourceUri, string xsltUri) { //SaxonController saxon = new SaxonController(); //saxon.XmlToStream(@"D:\test.xml", @"D:\test.xsl"); //return View(); string sourceUri = @"D:\test.xml"; string xsltUri = @"D:\test.xsl"; //Processor属于Saxon.Api Processor processor = new Processor(); //加载源文档 XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri)); //为StyleSheet创建一个新的转换器 XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load(); transformer.InitialContextNode = input; transformer.BaseOutputUri = new Uri(xsltUri); // transformer.SetParameter(new QName("", "", "a-param"), new XdmAtomicValue("hello to you!")); // transformer.SetParameter(new QName("", "", "b-param"), new XdmAtomicValue(someVariable)); // Create a serializer. Serializer serializer = new Serializer(); serializer.SetOutputWriter(Response.Output); //for screen // serializer.SetOutputFile(Server.MapPath("test.html")); //for file // Transform the source XML to System.out. transformer.Run(serializer); }
public void SimpleTransformTest() { var xslt = Path.Combine(Helper.GetDataPath(), "Sample.xslt"); var output = Path.Combine(Helper.GetDataPath(), "Sample.xml"); if (File.Exists(output)) { File.Delete(output); } var transformer = new XsltTransformer(xslt, output, GetKeyValueCollection()); transformer.Transform(); XmlDocument doc = new XmlDocument(); doc.Load(output); var nameNodes = doc.SelectNodes("configuration/appSettings/add[@key = 'Name' and @value = 'Value']"); var emailNodes = doc.SelectNodes("configuration/appSettings/add[@key = 'Email' and @value = '*****@*****.**']"); var companyNodes = doc.SelectNodes("configuration/appSettings/add[@key = 'Company' and @value = 'IBM']"); Assert.AreEqual(nameNodes.Count, 1); Assert.AreEqual(emailNodes.Count, 1); Assert.AreEqual(companyNodes.Count, 1); }
protected override void Execute(EditorFrame ef) { try { var encoding = XSConfiguration.Instance.Config.Encoding; XmlDocument xml; string xslt; if (ef.Data.XsltData.XmlInEditor) { xml = ef.XmlEditor.Text.ToXmlDocument(); xslt = File.ReadAllText(ef.Data.XsltData.File); } else { string x = File.ReadAllText(ef.Data.XsltData.File); xml = x.ToXmlDocument(); xslt = ef.XmlEditor.Text; } var result = new XsltTransformer().Transform(xml, xslt, encoding); SetResult(result); } catch (Exception ex) { string exc = ex.Message; if (ex.InnerException != null) { exc += ex.InnerException.Message; } MessageBox.Show(Application.Current.MainWindow, "Error: " + exc, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
static void Main(string[] args) { string xml = string.Empty; string xslt = string.Empty; string xmlSourceFile = string.Empty; string xsltTransformFile = string.Empty; string outputFile = string.Empty; StringBuilder errorLine = new StringBuilder(); StringBuilder argumentsPassedIn = new StringBuilder(); if (args.Length != 3) { errorLine.AppendLine("Faulty command line format. Not enough arguments. Check your command line format." + args.Length.ToString()); Console.WriteLine(errorLine.ToString() + "\n\nPress any key to quit program, and fix command line"); Console.ReadKey(); return; } xmlSourceFile = args.Where(c => c.Contains("/xml=")).FirstOrDefault(); xsltTransformFile = args.Where(c => c.Contains("/xsl=")).FirstOrDefault(); outputFile = args.Where(c => c.Contains("/out=")).FirstOrDefault(); argumentsPassedIn.AppendLine("\n\nHere are your arguments:"); argumentsPassedIn.AppendLine(xmlSourceFile); argumentsPassedIn.AppendLine(xsltTransformFile); argumentsPassedIn.AppendLine(outputFile); if (string.IsNullOrEmpty(xmlSourceFile) || string.IsNullOrEmpty(xsltTransformFile) || string.IsNullOrEmpty(outputFile)) { errorLine.AppendLine("Faulty command line format. Check your command line format. Make sure all file paths are surrounded by double quotes. " + "The switches required are xml=\"[your xml file name]\", xsl=\"[xslt stylesheet]\", and out=\"[your output file]\"" + argumentsPassedIn.ToString()); } xmlSourceFile = xmlSourceFile.Replace("/xml=", ""); xsltTransformFile = xsltTransformFile.Replace("/xsl=", ""); outputFile = outputFile.Replace("/out=", ""); xutil = new XmlUtility(); transformer = new XsltTransformer(); try { xml = xutil.ReadXmlFile(xmlSourceFile); xslt = transformer.ReadStyleSheet(xsltTransformFile); transformer.Transform(xml, xslt, outputFile); Console.WriteLine("Transformation succeeded"); } catch (Exception ex) { Console.WriteLine("Error in transformation: " + ex.Message + "\n\n" + errorLine.ToString() + argumentsPassedIn.ToString()); } Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
private void RunSchematron() { Uri baseuri = new Uri(@"D:\VisualStudio Projects\HL7\SchematronTrySaxon.ConsoleApplication\"); Uri baseuri2 = new Uri(@"D:\VisualStudio Projects\HL7\SchematronTry.ConsoleApplication\"); // Create a Processor instance. Processor processor = new Processor(); XsltCompiler compiler = processor.NewXsltCompiler(); DocumentBuilder builder = processor.NewDocumentBuilder(); builder.XmlResolver = new UserXmlResolver(); //builder.BaseUri = baseuri; // Transform the Schematron // Create a transformer for the stylesheet. XsltTransformer transformer = compiler.Compile(new Uri(baseuri, @"iso-schematron-xslt2\iso_svrl_for_xslt2.xsl")).Load(); // Load the source document XdmNode input = builder.Build(new Uri(baseuri, @"Test2.sch")); // XdmNode input = builder.Build(new Uri(baseuri, @"Test3.sch")); // Set the root node of the source document to be the initial context node transformer.InitialContextNode = input; // Create a serializer, with output to the standard output stream Serializer serializer = new Serializer(); serializer.SetOutputFile(@"D:\VisualStudio Projects\HL7\SchematronTrySaxon.ConsoleApplication\Test2.sch.xsl"); // StringWriter schxsl = new StringWriter(); // serializer.SetOutputWriter(schxsl); // Transform the source XML and serialize the result document transformer.Run(serializer); // Execute the Schematron // Create a transformer for the stylesheet. XsltTransformer transformer2 = compiler.Compile(new Uri(@"D:\VisualStudio Projects\HL7\SchematronTrySaxon.ConsoleApplication\Test2.sch.xsl")).Load(); //XsltTransformer transformer2 = compiler.Compile(new StringReader(schxsl.GetStringBuilder().ToString())).Load(); // Load the source document // XdmNode input2 = builder.Build(new Uri(baseuri2, @"fm-max.xml")); XdmNode input2 = builder.Build(new Uri(baseuri, @"XMLFile1.xml")); // Set the root node of the source document to be the initial context node transformer2.InitialContextNode = input; // Create a serializer, with output to the standard output stream Serializer serializer2 = new Serializer(); serializer2.SetOutputFile(@"D:\VisualStudio Projects\HL7\SchematronTrySaxon.ConsoleApplication\fm-max.xml-output"); // Transform the source XML and serialize the result document transformer2.Run(serializer2); }
/// <summary> /// A generic XSL Transformation [v2.0] Class for use in ASP.NET pages /// </summary> public static string TransformXml2(string xmlPath, string xsltPath, Hashtable xsltParams, string output) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); try { // Create a Processor instance. Processor processor = new Processor(); // Load the source document. XdmNode input = processor.NewDocumentBuilder().Build(new Uri(xmlPath)); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltPath)).Load(); // Set the root node of the source document to be the initial context node. transformer.InitialContextNode = input; // BaseOutputUri is only necessary for xsl:result-document (might be able to use xsl:result-document for alternative file output) transformer.BaseOutputUri = new Uri(xsltPath); //Fill XsltArgumentList if necessary - taken from key/value pairs in the hashtable if (xsltParams != null) { IDictionaryEnumerator pEnumerator = xsltParams.GetEnumerator(); while (pEnumerator.MoveNext()) { transformer.SetParameter(new QName("", "", pEnumerator.Key.ToString()), new XdmAtomicValue(pEnumerator.Value.ToString())); } } // Create a serializer and run it over the result of the transform. Serializer serializer = new Serializer(); serializer.SetOutputWriter(sw); transformer.Run(serializer); // Output method (though keep in mind this can't be written to a file if using ASP.net controls because it is not yet processed) if (output == "file") { TextWriter w = new StreamWriter(@"c:\inetpub\wwwroot\output.html"); w.Write(sb.ToString()); w.Close(); } return sb.ToString(); } catch (Exception exp) { return exp.ToString(); } finally { sw.Close(); } }
public static void TransformXmlFile(string xmlFileFullPathAndName, string styleSheetFileFullPathAndName, string outputfileFullPathAndName) { var inputReader = new XmlUtility(); var transformer = new XsltTransformer(); string input = inputReader.ReadXmlFile(xmlFileFullPathAndName); string style = transformer.ReadStyleSheet(styleSheetFileFullPathAndName); transformer.Transform(input, style, outputfileFullPathAndName); }
public SaxonTransformer(string strTransformerFilePath, ILogger logger) { _logger = logger; var processor = new Processor(); using (var stream = File.OpenRead(strTransformerFilePath)) { _transformer = processor.NewXsltCompiler().Compile(stream).Load(); } }
private string TransformXmltoHtml(string xmlOutput) { string outputFilename = xmlOutput + ".html"; using (XmlWriter output = XmlWriter.Create(outputFilename)) { var input = new XPathDocument(xmlOutput); XsltTransformer.Transform(input, output); } return(outputFilename); }
public void ApplicatioSettings() { var xslt = Path.Combine(Helper.GetDataPath(), "ApplicationSettings.xslt"); var output = Path.Combine(Helper.GetDataPath(), "ApplicationSettings.xml"); if (File.Exists(output)) File.Delete(output); var expected = GetKeyValueCollection(); var transformer = new XsltTransformer(xslt, output, expected); transformer.Transform(); var actual = GetApplicationSettingsFromFile(output); Assert.AreEqual(expected.Count, actual.Count); }
public void SimpleTransformTest() { var xslt = Path.Combine(Helper.GetDataPath(), "Sample.xslt"); var output = Path.Combine(Helper.GetDataPath(), "Sample.xml"); if (File.Exists(output)) File.Delete(output); var transformer = new XsltTransformer(xslt, output, GetKeyValueCollection()); transformer.Transform(); XmlDocument doc = new XmlDocument(); doc.Load(output); var nameNodes = doc.SelectNodes("configuration/appSettings/add[@key = 'Name' and @value = 'Value']"); var emailNodes = doc.SelectNodes("configuration/appSettings/add[@key = 'Email' and @value = '*****@*****.**']"); var companyNodes = doc.SelectNodes("configuration/appSettings/add[@key = 'Company' and @value = 'IBM']"); Assert.AreEqual(nameNodes.Count, 1); Assert.AreEqual(emailNodes.Count, 1); Assert.AreEqual(companyNodes.Count, 1); }