private XsltExecutable GetXsltExecutable(string xslt) { var cacheEntry = _cache.Get <XsltExecutable>(XsltCacheRegion, xslt); if (cacheEntry?.Value != null) { return(cacheEntry.Value); } var processor = new Processor(); XsltCompiler compiler = processor.NewXsltCompiler(); // create stream from input xslt string fullXslt = "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + "<xsl:output method=\"text\" />" + $"{xslt}" + $"<xsl:template match=\"/*\" priority=\"0\">{NoMatchString}</xsl:template></xsl:stylesheet>"; byte[] xsltByteArray = System.Text.Encoding.UTF8.GetBytes(fullXslt); var xsltStream = new MemoryStream(xsltByteArray); XsltExecutable xsltExecutable = compiler.Compile(xsltStream); _cache.Set(XsltCacheRegion, xslt, xsltExecutable); return(xsltExecutable); }
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); } }
public override void ResetVariables() { sourceDocument = null; stylesheet = null; resultDocument = null; resultFile = null; }
/** * 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 }
public XsltRunner(string stylesheetPath) { this.StylesheetPath = stylesheetPath; // Save a builder for later. _builder = _processor.NewDocumentBuilder(); // Handles the stylesheet compilation. var compiler = _processor.NewXsltCompiler(); // Load a stylesheet at a from text reader, v9.6 doesent like using a Uri for some reason. compiler.BaseUri = new Uri(Path.GetFullPath(this.StylesheetPath)); TextReader textreader = File.OpenText(stylesheetPath); var errorListener = new TransformerErrorListener(); try { compiler.GetUnderlyingCompilerInfo().setErrorListener(errorListener); _executable = compiler.Compile(textreader); } catch (TransformerException) { this.ReportCompilerErrors(errorListener); } }
/** * 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); }
internal static XsltInvoker With(IXPathNavigable stylesheet, IXsltProcessor processor, Assembly callingAssembly, out int hashCode) { if (stylesheet == null) { throw new ArgumentNullException("stylesheet"); } if (processor == null) { processor = Processors.Xslt.DefaultProcessor; } hashCode = XPathNavigatorEqualityComparer.Instance.GetHashCode(stylesheet.CreateNavigator()); ConcurrentDictionary <int, XsltExecutable> cache = inlineCache.GetOrAdd(processor, p => new ConcurrentDictionary <int, XsltExecutable>()); XsltExecutable exec = cache.GetOrAdd(hashCode, i => { var resolver = new XmlDynamicResolver(callingAssembly); return(processor.Compile(stylesheet, new XsltCompileOptions { XmlResolver = resolver })); }); return(new XsltInvoker(exec, callingAssembly)); }
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); }
static XsltInvoker With(Uri stylesheetUri, IXsltProcessor processor, Assembly callingAssembly) { if (stylesheetUri == null) { throw new ArgumentNullException("stylesheetUri"); } var resolver = new XmlDynamicResolver(callingAssembly); if (!stylesheetUri.IsAbsoluteUri) { stylesheetUri = resolver.ResolveUri(null, stylesheetUri.OriginalString); } if (processor == null) { processor = Processors.Xslt.DefaultProcessor; } ConcurrentDictionary <Uri, XsltExecutable> cache = uriCache.GetOrAdd(processor, p => new ConcurrentDictionary <Uri, XsltExecutable>()); XsltExecutable executable = cache.GetOrAdd(stylesheetUri, u => { using (var stylesheetSource = (Stream)resolver.GetEntity(stylesheetUri, null, typeof(Stream))) { return(processor.Compile(stylesheetSource, new XsltCompileOptions { BaseUri = stylesheetUri, XmlResolver = resolver })); } }); return(new XsltInvoker(executable, callingAssembly)); }
///<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); }
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 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()); } }
public static string TransformXMLToHTML(Stream input, Stream transformXsl, Stream output) { try { Processor xsltProcessor = new Processor(); XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler(); XsltExecutable xsltExecutable = xsltCompiler.Compile(transformXsl); var xsltTransformer = xsltExecutable.Load(); XmlTextReader modelFileXML = new XmlTextReader(input); XdmNode xdmNode = xsltProcessor.NewDocumentBuilder().Build(modelFileXML); xsltTransformer.InitialContextNode = xdmNode; Serializer serializer = xsltProcessor.NewSerializer(); serializer.SetOutputStream(output); xsltTransformer.Run(serializer); return(""); } catch (Exception e) { MessageBox.Show(e.Message + "\r\n" + e.StackTrace); return(string.Empty); } }
/** * 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); }
private XsltExecutable getXhtmlCanonizer(Processor p) { if (xhtmlCanonizer == null) { xhtmlCanonizer = p.NewXsltCompiler().Compile( new FileStream(testSuiteDir + "/SaxonResults/canonizeXhtml.xsl", FileMode.Open)); } return(xhtmlCanonizer); }
protected internal XsltSchematronValidator(XsltExecutable executable) { if (executable == null) { throw new ArgumentNullException("executable"); } this.executable = executable; }
private XsltExecutable getXhtmlCanonizer(Processor p) { if (xhtmlCanonizer == null) { xhtmlCanonizer = p.NewXsltCompiler().Compile( new FileStream(comparerDir + "/canonizeXhtml.xsl", FileMode.Open)); } return(xhtmlCanonizer); }
public override void ResetVariables() { documentBuilder = null; sourceDocument = null; stylesheet = null; resultDocument = null; resultFile = null; schemaAware = false; processor.SetProperty(net.sf.saxon.lib.FeatureKeys.SCHEMA_VALIDATION_MODE, "strip"); }
public ActionResult Upload(IEnumerable <HttpPostedFileBase> fileUpload) { foreach (var file in fileUpload) { if (Request.Files.Count > 0) { if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Files/"), fileName); var extension = Path.GetExtension(file.FileName); //dosya uzantısını aldım switch (extension) // Uzantıya göre texareaya yönlendirdim { case ".xml": ViewBag.mesaj = System.IO.File.ReadAllText(path); localPathXml = path; break; case ".xslt": ViewBag.mesaj2 = System.IO.File.ReadAllText(path); localPathXslt = path; break; } SaveExtension = extension; } } } //Dosyalar upload edildikten sonra Saxon HE ile tranform işlemi yap Processor xsltProcessor = new Processor(); DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder(); documentBuilder.BaseUri = new Uri("file://"); XdmNode xdmNode = documentBuilder.Build(new StringReader(ViewBag.mesaj)); XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler(); XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(ViewBag.mesaj2)); XsltTransformer xsltTransformer = xsltExecutable.Load(); xsltTransformer.InitialContextNode = xdmNode; using (StringWriter stringWriter = new StringWriter()) { Serializer serializer = new Serializer(); serializer.SetOutputWriter(stringWriter); xsltTransformer.Run(serializer); ViewBag.cikti = stringWriter; } return(View("Index")); }
//run an XSLT transform. //transformFile is the name of the .xsl to run; //path is usually tools directory (be sure to include final slash in passed string) //takes two paramaters and corresponding values; use empty strings if not needed static public XmlDocument performTransformWith2Params(XmlDocument inDOM, string path, string transformFile, string param1Name, string param1Value, string param2Name, string param2Value) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document, building a tree XmlNode node = inDOM; XdmNode input = processor.NewDocumentBuilder().Build(node); // Compile the stylesheet XsltExecutable exec = processor.NewXsltCompiler().Compile(new XmlTextReader(path.Replace("Program Files", "PROGRA~1") + transformFile)); // Create a transformer XsltTransformer transformer = exec.Load(); string xdmToolsPath = "file:/" + path.Replace("\\", "/").Replace(" ", "%20"); // Run it once // Set parameters transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false)); //following may be needed if xslt itself needs to find other files transformer.SetParameter(new QName("", "", "localBaseUri"), new XdmAtomicValue(xdmToolsPath.Replace("Program%20Files", "PROGRA~1"))); //optionally add another parameter if (!String.IsNullOrEmpty(param1Name)) { transformer.SetParameter(new QName("", "", param1Name), new XdmAtomicValue(param1Value)); } //and another param if (!String.IsNullOrEmpty(param2Name)) { transformer.SetParameter(new QName("", "", param2Name), new XdmAtomicValue(param2Value)); } transformer.InitialContextNode = input; XdmDestination results = new XdmDestination(); transformer.Run(results); XmlDocument resultXmlDoc = new XmlDocument(); resultXmlDoc.LoadXml(results.XdmNode.OuterXml); XmlDeclaration declaration = resultXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); resultXmlDoc.PrependChild(declaration); // return the result return(resultXmlDoc); }
private String canonizeXhtml(Processor p, String input) { try { XsltExecutable canonizer = getXhtmlCanonizer(p); XsltTransformer t = canonizer.Load(); StringWriter sw = new StringWriter(); Serializer r = new Serializer(); r.SetOutputWriter(sw); t.InitialContextNode = p.NewDocumentBuilder().Build( new FileStream(input, FileMode.Open)); t.Run(r); return(sw.ToString()); } catch (Exception err) { Console.WriteLine("*** Failed to compile or run XHTML canonicalizer stylesheet: " + err.ToString()); } return(""); }
public string InvoiceTransform(string code, string code2) { string invoiceHtml = String.Empty; if (code == "" || code2 == "") { Response.Write("<script lang='JavaScript'>alert('Dosyaları Yüklemeden Kaydetme İşlemi Gerçekleşmez');</script>"); } else { //textarealardaki değişikliklerini hafızaya kaydet MemoryStream Xml = new MemoryStream(Encoding.UTF8.GetBytes(code)); Xml.Write(System.Text.Encoding.UTF8.GetBytes(code), 0, code.Length); ViewBag.mesaj = code; MemoryStream Xslt = new MemoryStream(Encoding.UTF8.GetBytes(code2)); Xslt.Write(System.Text.Encoding.UTF8.GetBytes(code2), 0, code2.Length); ViewBag.mesaj2 = code2; localXmlString = ViewBag.mesaj; localXsltString = ViewBag.mesaj2; Processor xsltProcessor = new Processor(); DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder(); documentBuilder.BaseUri = new Uri("file://"); XdmNode xdmNode = documentBuilder.Build(new StringReader(code)); XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler(); XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(code2)); XsltTransformer xsltTransformer = xsltExecutable.Load(); xsltTransformer.InitialContextNode = xdmNode; using (StringWriter stringWriter = new StringWriter()) { Serializer serializer = new Serializer(); serializer.SetOutputWriter(stringWriter); xsltTransformer.Run(serializer); ViewBag.cikti = stringWriter; invoiceHtml = stringWriter.ToString(); } } return(invoiceHtml); }
/// <summary> /// Compare two XML files /// </summary> /// <param name="actual">The URI of the first file</param> /// <param name="gold">The URI of the second file</param> /// <returns></returns> private String compareXML(String actual, String gold) { try { if (xmlComparer == null) { xmlComparer = processor.NewXsltCompiler().Compile(new Uri(comparerDir + "/compare.xsl")); } XdmNode doc1 = processor.NewDocumentBuilder().Build(new Uri(actual)); XdmNode doc2 = processor.NewDocumentBuilder().Build(new Uri(gold)); return(compareDocs(doc1, doc2)); } catch (Exception e) { Console.WriteLine("***" + e.Message); return("XML comparison failure: " + e.Message); } }
public static void Transform(string styleSheet, string inputFile, string outputFile) { Processor processor = new Processor(); var uriInput = new System.Uri(inputFile); var uriStyleSheet = new System.Uri(styleSheet); XdmNode inputXdmNode = processor.NewDocumentBuilder().Build(uriInput); XsltCompiler xsltCompiler = processor.NewXsltCompiler(); XsltExecutable xsltExecutable = xsltCompiler.Compile(uriStyleSheet); XsltTransformer xsltTransformer = xsltExecutable.Load(); xsltTransformer.InitialContextNode = inputXdmNode; Serializer serializer = processor.NewSerializer(); StreamWriter streamWriter = new StreamWriter(outputFile); serializer.SetOutputWriter(streamWriter); xsltTransformer.Run(serializer); streamWriter.Close(); }
internal XsltResultHandler(XsltExecutable executable, XsltRuntimeOptions options) { this.executable = executable; this.options = options; this.defaultSerialization = options.Serialization; }
protected string runXSLT(String testName, String xml, String xsl, QName initialMode, QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath, bool useAssociated, bool schemaAware, String validationMode, bool recoverRecoverable) { Serializer sr = new Serializer(); sr.SetOutputFile(outfile); Processor f; //if (noCacheTests.contains(testName) || testName.startsWith("schemaas20") || // testName.startsWith("striptype20") || testName.startsWith("notation20")) { // create a custom Processor to avoid schema caching //} else { if (schemaAware) { f = schemaAwareProcessor; } else if (xml11) { f = processor; // Use an Xml 1.1 processor } else { f = processor; } //} XdmNode source = null; IList errors = new ArrayList(); XsltCompiler compiler = f.NewXsltCompiler(); compiler.ErrorList = errors; XsltExecutable sheet = null; XsltTransformer inst; if (useAssociated) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { Console.WriteLine("Failed to build source document: " + e.Message); return("ErrorBBB"); } try { sheet = compiler.CompileAssociatedStylesheet(source); } catch (Exception e) { Console.WriteLine("Failed to compile stylesheet: " + e.Message); if (errors.Count > 0) { QName code = ((StaticError)errors[0]).ErrorCode; return(code == null ? "ErrorXXX" : code.LocalName); } else { return("ErrorXXX"); } } } else { Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read); compiler.BaseUri = new Uri(xsl); try { sheet = compiler.Compile(stream); } catch (Exception e) { if (errors.Count > 0) { return(((StaticError)errors[0]).ErrorCode.LocalName); } else { Console.WriteLine(e.Message); return("ErrorXXX"); } } finally { stream.Close(); } } if (source == null && xml != null) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { Console.WriteLine("Failed to build source document: " + e.Message); return("ErrorCCC"); } } if (initialContextPath != null) { XPathCompiler xc = f.NewXPathCompiler(); XPathExecutable exp = xc.Compile(initialContextPath); XPathSelector xpe = exp.Load(); xpe.ContextItem = source; XdmNode node = (XdmNode)xpe.EvaluateSingle(); source = node; } inst = sheet.Load(); if (initialMode != null) { inst.InitialMode = initialMode; } if (initialTemplate != null) { try { inst.InitialTemplate = initialTemplate; } catch (DynamicError e) { QName code = e.ErrorCode; if (code != null) { return(code.LocalName); } else { return("ErrYYYYY"); } } } if (paramTable != null) { foreach (DictionaryEntry de in paramTable) { inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString())); } } inst.InitialContextNode = source; //inst.setURIResolver(factory.getURIResolver()); //inst.setErrorListener(errorListener); //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER); // To avoid test results being dependent on the date and time (and timezone), set a fixed // date and time for the run //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00")); try { inst.Run(sr); } catch (DynamicError e) { Console.WriteLine(e.Message); QName code = e.ErrorCode; if (code != null) { return(code.LocalName); } else { return("ErrYYYYY"); } } return(null); // indicating success }
public override void CompileStylesheet(Uri stylesheetUri) { stylesheet = compiler.Compile(stylesheetUri); }
private XsltInvoker(XsltExecutable executable, Assembly withCallingAssembly) { this.executable = executable; this.withCallingAssembly = withCallingAssembly; }
protected override void runTestCase(XdmNode testCase, XPathCompiler xpath) { TestOutcome outcome = new TestOutcome(this); string testName = testCase.GetAttributeValue(new QName("name")); string testSetName = testCase.Parent.GetAttributeValue(new QName("name")); //// if (testName.Equals("type-0174")) { int num = 0; System.Console.WriteLine("Test driver" + num); } /// if (exceptionsMap.ContainsKey(testName)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason"))); return; } if (exceptionsMap.ContainsKey(testName) || isSlow(testName)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources"); return; } XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase)); string spec = specAtt.ToString(); Environment env = getEnvironment(testCase, xpath); if (env == null) { resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error"); return; } /*if(testName("environment-variable")) { * EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() { * public Set<string> getAvailableEnvironmentVariables() { * Set<string> strings = new HashSet<string>(); * strings.add("QTTEST"); * strings.add("QTTEST2"); * strings.add("QTTESTEMPTY"); * return strings; * } * * public string getEnvironmentVariable(string name) { * if (name.Equals("QTTEST")) { * return "42"; * } else if (name.Equals("QTTEST2")) { * return "other"; * } else if (name.Equals("QTTESTEMPTY")) { * return ""; * } else { * return null; * } * } * }; //TODO * } */ // env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO XdmNode testInput = (XdmNode)xpath.EvaluateSingle("test", testCase); XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput); XdmNode pack = (XdmNode)xpath.EvaluateSingle("package", testInput); foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase)) { if (!dependencyIsSatisfied((XdmNode)dep, env)) { notrun++; resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied"); return; } } XsltExecutable sheet = env.xsltExecutable; //ErrorCollector collector = new ErrorCollector(); string baseOutputURI = resultsDir + "/results/output.xml"; ErrorCollector collector = new ErrorCollector(outcome); IList errorList = new List <StaticError> (); XmlUrlResolver res = new XmlUrlResolver(); string xsltLanguageVersion = spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"; if (stylesheet != null) { XsltCompiler compiler = env.xsltCompiler; compiler.ErrorList = errorList; Uri hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file"))); Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read); compiler.BaseUri = hrefFile; compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"); foreach (XdmItem param in xpath.Evaluate("param[@static='yes']", testInput)) { String name = ((XdmNode)param).GetAttributeValue(new QName("name")); String select = ((XdmNode)param).GetAttributeValue(new QName("select")); XdmValue value; try { value = xpath.Evaluate(select, null); } catch (Exception e) { Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message); //throw e; continue; } compiler.SetParameter(new QName(name), value); } try { sheet = compiler.Compile(stream); } catch (Exception err) { Console.WriteLine(err.Message); //Console.WriteLine(err.StackTrace); IEnumerator enumerator = errorList.GetEnumerator(); bool checkCur = enumerator.MoveNext(); /*if (checkCur && enumerator.Current != null) { * outcome.SetException ((Exception)(enumerator.Current)); * } else { * Console.WriteLine ("Error: Unknown exception thrown"); * }*/ outcome.SetErrorsReported(errorList); //outcome.SetErrorsReported(collector.GetErrorCodes); } // compiler.setErrorListener(collector); } else if (pack != null) { Uri hrefFile = res.ResolveUri(pack.BaseUri, pack.GetAttributeValue(new QName("file"))); Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read); XsltCompiler compiler = env.xsltCompiler; compiler.ErrorList = errorList; compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0"); //compiler.setErrorListener(collector); try { XsltPackage xpack = compiler.CompilePackage(stream); sheet = xpack.Link(); } catch (Exception err) { Console.WriteLine(err.Message); IEnumerator enumerator = errorList.GetEnumerator(); enumerator.MoveNext(); outcome.SetException((Exception)(enumerator.Current)); outcome.SetErrorsReported(errorList); } } if (sheet != null) { XdmItem contextItem = env.contextItem; XdmNode initialMode = (XdmNode)xpath.EvaluateSingle("initial-mode", testInput); XdmNode initialFunction = (XdmNode)xpath.EvaluateSingle("initial-function", testInput); XdmNode initialTemplate = (XdmNode)xpath.EvaluateSingle("initial-template", testInput); QName initialModeName = GetQNameAttribute(xpath, testInput, "initial-mode/@name"); QName initialTemplateName = GetQNameAttribute(xpath, testInput, "initial-template/@name"); if (useXslt30Transformer) { try { bool assertsSerial = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0; bool resultAsTree = env.outputTree; bool serializationDeclared = env.outputSerialize; XdmNode needsTree = (XdmNode)xpath.EvaluateSingle("output/@tree", testInput); if (needsTree != null) { resultAsTree = needsTree.StringValue.Equals("yes"); } XdmNode needsSerialization = (XdmNode)xpath.EvaluateSingle("output/@serialize", testInput); if (needsSerialization != null) { serializationDeclared = needsSerialization.StringValue.Equals("yes"); } bool resultSerialized = serializationDeclared || assertsSerial; if (assertsSerial) { String comment = outcome.GetComment(); comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* "); outcome.SetComment(comment); } Xslt30Transformer transformer = sheet.Load30(); transformer.InputXmlResolver = env; if (env.unparsedTextResolver != null) { transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver); } Dictionary <QName, XdmValue> caseGlobalParams = GetNamedParameters(xpath, testInput, false, false); Dictionary <QName, XdmValue> caseStaticParams = GetNamedParameters(xpath, testInput, true, false); Dictionary <QName, XdmValue> globalParams = new Dictionary <QName, XdmValue>(env.params1); foreach (KeyValuePair <QName, XdmValue> entry in caseGlobalParams) { globalParams.Add(entry.Key, entry.Value); } foreach (KeyValuePair <QName, XdmValue> entry in caseStaticParams) { globalParams.Add(entry.Key, entry.Value); } transformer.SetStylesheetParameters(globalParams); if (contextItem != null) { transformer.GlobalContextItem = contextItem; } transformer.MessageListener = collector; transformer.BaseOutputURI = baseOutputURI; transformer.MessageListener = new TestOutcome.MessageListener(outcome); XdmValue result = null; TextWriter sw = new StringWriter(); Serializer serializer = env.processor.NewSerializer(); serializer.SetOutputWriter(sw); //serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes"); OutputResolver serializingOutput = new OutputResolver(env.processor, outcome, true); net.sf.saxon.Controller controller = transformer.GetUnderlyingController; controller.setOutputURIResolver(serializingOutput); XmlDestination dest = null; if (resultAsTree) { // If we want non-serialized, we need to accumulate any result documents as trees too controller.setOutputURIResolver( new OutputResolver(env.processor, outcome, false)); dest = new XdmDestination(); } if (resultSerialized) { dest = serializer; } Stream src = null; Uri srcBaseUri = new Uri("http://uri"); XdmNode srcNode = null; DocumentBuilder builder2 = env.processor.NewDocumentBuilder(); if (env.streamedPath != null) { src = new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read); srcBaseUri = new Uri(env.streamedPath); } else if (env.streamedContent != null) { byte[] byteArray = Encoding.UTF8.GetBytes(env.streamedContent); src = new MemoryStream(byteArray); //, "inlineDoc"); builder2.BaseUri = new Uri("http://uri"); } else if (initialTemplate == null && contextItem != null) { srcNode = (XdmNode)(contextItem); } if (initialMode != null) { QName name = GetQNameAttribute(xpath, initialMode, "@name"); try { if (name != null) { transformer.InitialMode = name; } else { controller.getInitialMode(); /// has the side effect of setting to the unnamed } } catch (Exception e) { if (e.InnerException is net.sf.saxon.trans.XPathException) { Console.WriteLine(e.Message); outcome.SetException(e); //throw new SaxonApiException(e.getCause()); } else { throw e; } } } if (initialMode != null || initialTemplate != null) { XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode); Dictionary <QName, XdmValue> params1 = GetNamedParameters(xpath, init, false, false); Dictionary <QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true); if (xsltLanguageVersion.Equals("2.0")) { if (!(params1.Count == 0 && tunnelledParams.Count == 0)) { Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0"); } } else { transformer.SetInitialTemplateParameters(params1, false); transformer.SetInitialTemplateParameters(tunnelledParams, true); } } if (initialTemplate != null) { QName name = GetQNameAttribute(xpath, initialTemplate, "@name"); transformer.GlobalContextItem = contextItem; if (dest == null) { result = transformer.CallTemplate(name); } else { transformer.CallTemplate(name, dest); } } else if (initialFunction != null) { QName name = getQNameAttribute(xpath, initialFunction, "@name"); XdmValue[] params2 = getParameters(xpath, initialFunction); if (dest == null) { result = transformer.CallFunction(name, params2); } else { transformer.CallFunction(name, params2, dest); } } else { if (dest == null) { if (src != null) { result = transformer.ApplyTemplates(src, srcBaseUri); } else { result = transformer.ApplyTemplates(srcNode); } } else { if (src != null) { transformer.ApplyTemplates(src, dest); } else { transformer.ApplyTemplates(srcNode, dest); } } } //outcome.SetWarningsReported(collector.getFoundWarnings()); if (resultAsTree && !resultSerialized) { result = ((XdmDestination)(dest)).XdmNode; } if (resultSerialized) { outcome.SetPrincipalSerializedResult(sw.ToString()); } outcome.SetPrincipalResult(result); if (saveResults) { String s = sw.ToString(); // If a transform result is entirely xsl:result-document, then result will be null if (!resultSerialized && result != null) { StringWriter sw2 = new StringWriter(); Serializer se = env.processor.NewSerializer(sw2); se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); env.processor.WriteXdmValue(result, se); se.Close(); s = sw2.ToString(); } // currently, only save the principal result file in the result directory saveResultsToFile(s, resultsDir + "/results/" + testSetName + "/" + testName + ".out"); Dictionary <Uri, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.GetSecondaryResultDocuments(); foreach (KeyValuePair <Uri, TestOutcome.SingleResultDoc> entry in xslResultDocuments) { Uri key = entry.Key; String path = key.AbsolutePath; String serialization = outcome.Serialize(env.processor, entry.Value); saveResultsToFile(serialization, path); } } } catch (Exception err) { //if (err.getCause() is XPathException && //!((XPathException) err.getCause()).hasBeenReported()) { //System.err.println("Unreported ERROR: " + err.getCause()); //} outcome.SetException(err); if (collector.getErrorCodes().Count > 0) { outcome.SetErrorsReported((IList)collector.getErrorCodes()); } //Console.WriteLine(err.StackTrace); /*if(err.getErrorCode() == null) { * int b = 3 + 4; } * if(err.getErrorCode() != null) * outcome.AddReportedError(err.getErrorCode().getLocalName()); * } else { * outcome.SetErrorsReported(collector.getErrorCodes()); * }*/ } /*catch (Exception err) { * err.printStackTrace(); * failures++; * resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage()); * return; * }*/ } else { try { XsltTransformer transformer = sheet.Load(); //transformer.SetURIResolver(env); //TODO if (env.unparsedTextResolver != null) { transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver); } if (initialTemplate != null) { transformer.InitialTemplate = initialTemplateName; } if (initialMode != null) { transformer.InitialMode = initialModeName; } foreach (XdmItem param in xpath.Evaluate("param", testInput)) { string name = ((XdmNode)param).GetAttributeValue(new QName("name")); string select = ((XdmNode)param).GetAttributeValue(new QName("select")); XdmValue value = xpath.Evaluate(select, null); transformer.SetParameter(new QName(name), value); } if (contextItem != null) { transformer.InitialContextNode = (XdmNode)contextItem; } if (env.streamedPath != null) { transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); } foreach (QName varName in env.params1.Keys) { transformer.SetParameter(varName, env.params1[varName]); } //transformer.setErrorListener(collector); transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml"); /*transformer.MessageListener = (new MessageListener() { * public void message(XdmNode content, bool terminate, SourceLocator locator) { * outcome.addXslMessage(content); * } * });*/ // Run the transformation twice, once for serialized results, once for a tree. // TODO: we could be smarter about this and capture both // run with serialization StringWriter sw = new StringWriter(); Serializer serializer = env.processor.NewSerializer(sw); transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true)); transformer.Run(serializer); outcome.SetPrincipalSerializedResult(sw.ToString()); if (saveResults) { // currently, only save the principal result file saveResultsToFile(sw.ToString(), resultsDir + "/results/" + testSetName + "/" + testName + ".out"); } transformer.MessageListener = new TestOutcome.MessageListener(outcome); // run without serialization if (env.streamedPath != null) { transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); } XdmDestination destination = new XdmDestination(); transformer.Implementation.setOutputURIResolver( new OutputResolver(env.processor, outcome, false)); transformer.Run(destination); //transformer. .transform(); outcome.SetPrincipalResult(destination.XdmNode); //} } catch (Exception err) { outcome.SetException(err); //outcome.SetErrorsReported(collector.getErrorCodes()); // err.printStackTrace(); // failures++; //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message); //return; } } XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase); if (assertion == null) { failures++; resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found"); return; } XPathCompiler assertionXPath = env.processor.NewXPathCompiler(); //assertionXPath.setLanguageVersion("3.0"); bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug); if (success) { if (outcome.GetWrongErrorMessage() != null) { outcome.SetComment(outcome.GetWrongErrorMessage()); wrongErrorResults++; } else { successes++; } resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment()); } else { failures++; resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment()); } } }
public static string TransformXml(string xmlData, string xslData) { string results = ""; try { // Saxon Transformation Start Processor xsltProcessor = new Processor(); DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder(); documentBuilder.BaseUri = new Uri("file://"); XdmNode xdmNode = documentBuilder.Build(new StringReader(xmlData)); XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler(); XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(xslData)); XsltTransformer xsltTransformer = xsltExecutable.Load(); xsltTransformer.InitialContextNode = xdmNode; XdmDestination xdmDest = new XdmDestination(); xsltTransformer.Run(xdmDest); // Saxon Transformation End // Handle XML Declaration string version = "1.0"; string encoding = "UTF-8"; string standalone = null; string declaration = new XDeclaration(version, encoding, standalone).ToString() + Environment.NewLine; try { XDocument xslt = XDocument.Parse(xslData); XNamespace xsl = "http://www.w3.org/1999/XSL/Transform"; XElement elem = xslt.Root.Element(xsl + "output"); if (elem != null) { if (elem.Attribute("version") != null) { version = elem.Attribute("version").Value; } if (elem.Attribute("encoding") != null) { encoding = elem.Attribute("encoding").Value; } if (elem.Attribute("standalone") != null) { standalone = elem.Attribute("standalone").Value; } declaration = new XDeclaration(version, encoding, standalone).ToString() + Environment.NewLine; // Clear Declaration if (elem.Attribute("omit-xml-declaration") != null && elem.Attribute("omit-xml-declaration").Value == "yes") { declaration = ""; } if (elem.Attribute("method") != null && elem.Attribute("method").Value != "xml") { declaration = ""; } } // Attempt to prevent duplicate declaration if (xdmDest.XdmNode.OuterXml.StartsWith("<?")) { declaration = ""; } } catch { // ignore exception } results = declaration + xdmDest.XdmNode.OuterXml; } catch (Exception e) { throw e; } return(results); }