static void Main(string[] args) { String s1 = @"<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:output method='xml' indent='yes'/><xsl:template match='/'>"; String s2 = "This is running an XSLT engine by <xsl:value-of select=\"system-property('xsl:vendor')\" /> <a href=\"{system-property('xsl:vendor-url')}\"><xsl:value-of select=\"system-property('xsl:vendor-url')\" /></a> implementing XSLT v<xsl:value-of select=\"system-property('xsl:version')\" /> "; String s3 = @"\n<xsl:apply-templates/></xsl:template><xsl:template match='@*|node()'> "; String s4 = @"<xsl:copy><xsl:apply-templates select='@*|node()'/></xsl:copy></xsl:template></xsl:stylesheet>"; String str = s1 + s2 + s3 + s4; //Run Saxon //new SaxonTransform().doTransform(args, "Transform"); //Run Saxon s9 api // Create a Processor instance. Processor processor = new Processor(); // Load the source document. XdmNode input = processor.NewDocumentBuilder().Build(XmlReader.Create(new StringReader(str))); XsltCompiler compiler = processor.NewXsltCompiler(); //although it is not required in this example, we need to set otherwise exception will be thrown compiler.BaseUri = new Uri("http://dummyurl.com"); // Create a transformer for the stylesheet. XsltTransformer transformer = compiler.Compile(XmlReader.Create(new StringReader(str))).Load(); // BaseOutputUri is only necessary for xsl:result-document. //transformer.BaseOutputUri = new Uri("http://dummyurl.com"); // Set the root node of the source document to be the initial context node. transformer.InitialContextNode = input; transformer.SetParameter(new QName("", "", "maxmin"), new XdmAtomicValue("parm1")); transformer.SetParameter(new QName("", "", "pricestock"), new XdmAtomicValue("parm2")); // Create a serializer. Serializer serializer = new Serializer(); // Set the root node of the source document to be the initial context node //transformer.InitialTemplate = new QName("","","go"); serializer.SetOutputWriter(Console.Out); serializer.SetOutputProperty(Serializer.INDENT, "yes"); // serializer.SetOutputFile(Server.MapPath("test.html")); //for file // Transform the source XML to System.out. transformer.Run(serializer); //Call the SaxonMediator SaxonMediator mediator = new SaxonMediator(); //mediator.Transform(null, Template template, Package package) //wait for user to exit Console.ReadLine(); }
public void GenXML() { String sourceUri = Server.MapPath("5648.xml"); String xqUri = Server.MapPath("graph.xq"); using (FileStream sXml = File.OpenRead(sourceUri)) { using (FileStream sXq = File.OpenRead(xqUri)) { Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = sourceUri; XQueryExecutable exp = compiler.Compile(sXq); XQueryEvaluator eval = exp.Load(); DocumentBuilder loader = processor.NewDocumentBuilder(); loader.BaseUri = new Uri(sourceUri); XdmNode indoc = loader.Build(new FileStream(sourceUri, FileMode.Open, FileAccess.Read)); eval.ContextItem = indoc; Serializer qout = new Serializer(); qout.SetOutputProperty(Serializer.METHOD, "xml"); qout.SetOutputProperty(Serializer.INDENT, "yes"); qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1"); qout.SetOutputWriter(Response.Output); eval.Run(qout); } } }
public string serialize(Processor p) { if (isException()) { return "EXCEPTION " + exception.Message; } else { StringWriter sw = new StringWriter(); Serializer s = new Serializer(); s.SetOutputWriter(sw); s.SetOutputProperty(Serializer.METHOD, "xml"); s.SetOutputProperty(Serializer.INDENT, "yes"); s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); try { (new Processor()).WriteXdmValue(value, s); } catch (DynamicError err) { return ("SERIALIZATION FAILED: " + err.Message); } return sw.ToString(); } }
private bool testAssertion2(XdmNode assertion, Outcome outcome, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { string tag = assertion.NodeName.LocalName; if (tag.Equals("assert-eq")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile("$result eq " + assertion.StringValue).Load(); s.SetVariable(new QName("result"), outcome.getResult()); XdmAtomicValue item = (XdmAtomicValue)s.EvaluateSingle(); if (s == null) { return false; } return (bool)item.Value; } } if (tag.Equals("assert-deep-eq")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile("deep-equal($result , (" + assertion.StringValue + "))").Load(); s.SetVariable(new QName("result"), outcome.getResult()); return (bool)((XdmAtomicValue)s.Evaluate()).Value; } } else if (tag.Equals("assert-permutation")) { // TODO: extend this to handle nodes (if required) if (outcome.isException()) { return false; } else { try { int expectedItems = 0; Hashtable expected = new Hashtable(); XPathSelector s = assertXpc.Compile("(" + assertion.StringValue + ")").Load(); s.SetVariable(new QName("result"), outcome.getResult()); // not used, but we declared it net.sf.saxon.lib.StringCollator collator = net.sf.saxon.expr.sort.CodepointCollator.getInstance(); net.sf.saxon.expr.XPathContext context = new net.sf.saxon.expr.XPathContextMajor(net.sf.saxon.value.StringValue.EMPTY_STRING, assertXpc.Processor.Implementation); /* foreach (XdmItem item in s) { expectedItems++; XdmValue value = (XdmValue) item; Object comparable = value.isNaN() ? AtomicSortComparer.COLLATION_KEY_NaN : value.getXPathComparable(false, collator, context); expected.add(comparable); } */ int actualItems = 0; /*foreach (XdmItem item in outcome.getResult()) { actualItems++; AtomicValue value = (AtomicValue) item.getUnderlyingValue(); Object comparable = value.isNaN() ? AtomicSortComparer.COLLATION_KEY_NaN : value.getXPathComparable(false, collator, context); if (!expected.Contains(comparable)) { return false; } }*/ return actualItems == expectedItems; } catch (DynamicError e) { return false; } } } else if (tag.Equals("assert-serialization")) { if (outcome.isException()) { return false; } else { string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim())); string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes")); bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim())); catalogXpc.BaseUri = ""; string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString(); if (normalize) { comparand = net.sf.saxon.value.Whitespace.collapseWhitespace(comparand).ToString(); } StringWriter tw = new StringWriter(); Serializer serializer = new Serializer(); serializer.SetOutputWriter(tw); serializer.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "no"); serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); assertXpc.Processor.WriteXdmValue(outcome.getResult(), serializer); if (comparand.Equals(tw.ToString())) { return true; } DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder(); StringReader reader = new StringReader("<z>" + comparand + "</z>"); builder.BaseUri = assertion.BaseUri; XdmNode expected = builder.Build(reader); int flag = 0; flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_COMMENTS; flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS; if (!ignorePrefixes) { flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_NAMESPACES; flag |= net.sf.saxon.functions.DeepEqual.INCLUDE_PREFIXES; } flag |= net.sf.saxon.functions.DeepEqual.COMPARE_STRING_VALUES; flag |= net.sf.saxon.functions.DeepEqual.WARNING_IF_FALSE; try { net.sf.saxon.om.SequenceIterator iter0; XdmValue v = outcome.getResult(); if (v.Count == 1 && v is XdmNode && ((XdmNode)v).NodeKind == XmlNodeType.Document) { iter0 = ((XdmNode)v).Implementation.iterateAxis(net.sf.saxon.om.Axis.CHILD); } else { iter0 = net.sf.saxon.value.Value.asIterator(outcome.getResult().Unwrap()); } net.sf.saxon.om.SequenceIterator iter1 = (expected.Implementation.iterateAxis(net.sf.saxon.om.Axis.CHILD).next()).iterateAxis(net.sf.saxon.om.Axis.CHILD); return net.sf.saxon.functions.DeepEqual.deepEquals( iter0, iter1, new net.sf.saxon.expr.sort.GenericAtomicComparer(net.sf.saxon.expr.sort.CodepointCollator.getInstance(), null), assertXpc.Processor.Implementation, flag); } catch (DynamicError e) { // e.printStackTrace(); return false; } } } else if (tag.Equals("assert-serialization-error")) { if (outcome.isException()) { return false; } else { string expectedError = assertion.GetAttributeValue(new QName("code")); StringWriter sw = new StringWriter(); Serializer serializer = new Serializer(); serializer.SetOutputWriter(sw); serializer.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "no"); serializer.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes"); try { assertXpc.Processor.WriteXdmValue(outcome.getResult(), serializer); return false; } catch (DynamicError err) { bool b = expectedError.Equals(err.ErrorCode.LocalName); if (!b) { feedback.Message("Expected " + expectedError + ", got " + err.ErrorCode.LocalName, false); } return true; } } } else if (tag.Equals("assert-empty")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == 0; } } else if (tag.Equals("assert-count")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == int.Parse(assertion.StringValue); } } else if (tag.Equals("assert")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile(assertion.StringValue).Load(); s.SetVariable(new QName("result"), outcome.getResult()); return (bool)((XdmAtomicValue)s.EvaluateSingle()).Value; } } else if (tag.Equals("assert-string-value")) { if (outcome.isException()) { return false; } else { XdmValue resultValue = outcome.getResult(); string resultstring; string assertionstring = assertion.StringValue; if (resultValue is XdmNode) { resultstring = ((XdmNode)resultValue).StringValue; }else if(resultValue is XdmAtomicValue){ resultstring = ((XdmAtomicValue)resultValue).ToString(); } else { bool first = true; StringBuilder fsb = new StringBuilder(256); foreach (XdmItem item in resultValue) { if (first) { first = false; } else { fsb.Append(' '); } fsb.Append(item.Unwrap().getStringValue()); } resultstring = fsb.ToString(); } string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); if (normalizeAtt != null && (normalizeAtt.Trim().Equals("true") || normalizeAtt.Trim().Equals("1"))) { assertionstring = net.sf.saxon.value.Whitespace.collapseWhitespace(assertionstring).ToString(); resultstring = net.sf.saxon.value.Whitespace.collapseWhitespace(resultstring).ToString(); } if (resultstring.Equals(assertionstring)) { return true; } else { if (debug) { if (resultstring.Length != assertionstring.Length) { Console.WriteLine("Result length " + resultstring.Length + "; expected length " + assertionstring.Length); } int len = Math.Min(resultstring.Length, assertionstring.Length); for (int i = 0; i < len; i++) { if (resultstring[i] != assertionstring[i]) { feedback.Message("Results differ at index " + i + "(\"" + resultstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\") vs (\"" + assertionstring.Substring(i, (i + 10 > len ? len : i + 10)) + "\")", false); break; } } } return false; } } } else if (tag.Equals("assert-type")) { if (outcome.isException()) { return false; } else { XPathSelector s = assertXpc.Compile("$result instance of " + assertion.StringValue).Load(); s.SetVariable(new QName("result"), outcome.getResult()); return (bool)((XdmAtomicValue)s.EvaluateSingle()).Value; } } else if (tag.Equals("assert-true")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == 1 && ((XdmItem)result).IsAtomic() && ((XdmAtomicValue)result).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) && (((XdmAtomicValue)result).GetBooleanValue()); } } else if (tag.Equals("assert-false")) { if (outcome.isException()) { return false; } else { XdmValue result = outcome.getResult(); return result.Count == 1 && ((XdmItem)result.Simplify).IsAtomic() && ((XdmAtomicValue)result.Simplify).GetPrimitiveTypeName().Equals(QName.XS_BOOLEAN) && !(bool)((XdmAtomicValue)result.Simplify).Value; } } else if (tag.Equals("error")) { string expectedError = assertion.GetAttributeValue(new QName("code")); //noinspection ThrowableResultOfMethodCallIgnored Exception err = outcome.getException(); QName errorCode = null; if (err is DynamicError) { errorCode = ((DynamicError)outcome.getException()).ErrorCode; } else { errorCode = ((StaticError)outcome.getException()).ErrorCode; } return outcome.isException() && (expectedError.Equals("*") || (errorCode != null && errorCode.LocalName.Equals(expectedError)) || (outcome.hasReportedError(expectedError))); } else if (tag.Equals("all-of")) { XdmValue children = catalogXpc.Evaluate("*", assertion); foreach (XdmItem child in children) { if (!testAssertion((XdmNode)child, outcome, assertXpc, catalogXpc, debug)) { return false; } } return true; } else if (tag.Equals("any-of")) { XdmValue children = catalogXpc.Evaluate("*", assertion); foreach (XdmItem child in children) { if (testAssertion((XdmNode)child, outcome, assertXpc, catalogXpc, debug)) { return true; } } return false; } throw new Exception("Unknown assertion element " + tag); }
public void go(String[] args) { processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true"); testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } saxonResultsDir = args[1]; if (saxonResultsDir.EndsWith("/")) { saxonResultsDir = saxonResultsDir.Substring(0, testSuiteDir.Length - 1); } Hashtable exceptions = new Hashtable(); if (args.Length > 1) { testPattern = (args[2]); // TODO: allow a regex } for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-w")) { //showWarnings = true; } } fileComparer = new FileComparer(processor, testSuiteDir); XPathCompiler xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); xpc.DeclareVariable(new QName("", "param")); findSourcePath = xpc.Compile("//t:test-suite/t:sources/t:source[@ID=$param]"); findCollection = xpc.Compile("//t:test-suite/t:sources/t:collection[@ID=$param]"); xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); xpc.DeclareVariable(new QName("", "testcase")); xpc.DeclareVariable(new QName("", "moduleuri")); findModule = xpc.Compile("for $m in $testcase/t:module[@namespace=$moduleuri] " + "return concat('file:///" + testSuiteDir + "/', root($testcase)/t:test-suite/t:sources/t:module[@ID=string($m)]/@FileName, '.xq')"); //xpc = processor.NewXPathCompiler(); //xpc.DeclareNamespace("saxon", "http://saxon.sf.net/"); //xpc.DeclareVariable(new QName("", "actual")); //xpc.DeclareVariable(new QName("", "gold")); //xpc.DeclareVariable(new QName("", "debug")); //compareDocuments = xpc.Compile("saxon:deep-equal($actual, $gold, (), if ($debug) then 'JNCPS?!' else 'JNCPS')"); QName testCaseNT = new QName(testURI, "test-case"); QName nameNT = new QName(testURI, "name"); QName queryNT = new QName(testURI, "query"); QName inputNT = new QName(testURI, "input"); QName inputFileNT = new QName(testURI, "input-file"); QName inputUriNT = new QName(testURI, "input-URI"); QName defaultCollectionNT = new QName(testURI, "defaultCollection"); QName outputFileNT = new QName(testURI, "output-file"); QName expectedErrorNT = new QName(testURI, "expected-error"); QName schemaNT = new QName(testURI, "schema"); QName contextItemNT = new QName(testURI, "contextItem"); QName inputQueryNT = new QName(testURI, "input-query"); QName sourceDocumentNT = new QName(testURI, "source-document"); QName errorNT = new QName(testURI, "error"); QName validationNT = new QName(testURI, "validation"); QName discretionaryItemsNT = new QName(testURI, "discretionary-items"); QName discretionaryFeatureNT = new QName(testURI, "discretionary-feature"); QName discretionaryChoiceNT = new QName(testURI, "discretionary-choice"); QName initialContextNodeNT = new QName(testURI, "initial-context-node"); QName fileAtt = new QName("", "file"); QName filePathAtt = new QName("", "FilePath"); QName fileNameAtt = new QName("", "FileName"); QName errorIdAtt = new QName("", "error-id"); QName compareAtt = new QName("", "compare"); QName nameAtt = new QName("", "name"); QName behaviorAtt = new QName("", "behavior"); QName qnameAtt = new QName("", "qname"); QName modeAtt = new QName("", "mode"); QName validatesAtt = new QName("", "validates"); QName variableAtt = new QName("", "variable"); QName roleAtt = new QName("", "role"); DocumentBuilder builder = processor.NewDocumentBuilder(); XdmNode exceptionsDoc = builder.Build(new Uri(saxonResultsDir + "/exceptions-n.xml")); // The exceptions.xml file contains details of tests that aren't to be run, for example // because they have known bugs or require special configuration IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "exception")); while (exceptionTestCases.MoveNext()) { XdmNode n = (XdmNode)exceptionTestCases.Current; String nameAttVal = n.StringValue; char[] seps = { ' ', '\n', '\t' }; String[] parts = nameAttVal.Split(seps); foreach (string p in parts) { if (!exceptions.ContainsKey(p)) { exceptions.Add(p, "Exception"); } } } // Hash table containing all source documents. The key is the document name in the // catalog, the value is the corresponding document node Hashtable sourceDocs = new Hashtable(50); // Load the catalog XdmNode catalog = builder.Build(new Uri(testSuiteDir + "/XQTScatalog.xml")); // Add all Static Typing test cases to the exceptions list xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); XPathSelector st = xpc.Compile("//t:test-group[@name='StaticTyping']//t:test-case").Load(); st.ContextItem = catalog; IEnumerator ste = st.GetEnumerator(); while (ste.MoveNext()) { XdmNode testCase = (XdmNode)ste.Current; exceptions.Add(testCase.GetAttributeValue(nameAtt), "StaticTypingException"); } // Create the results file and log file results = new StreamWriter(saxonResultsDir + "/results" + processor.ProductVersion + "n.xml"); log = new StreamWriter(saxonResultsDir + "/log" + processor.ProductVersion + "n.xml"); log.WriteLine("Testing Saxon " + processor.ProductVersion); results.WriteLine("<test-suite-result xmlns='http://www.w3.org/2005/02/query-test-XQTSResult'>"); // Pre-load all the schemas SchemaManager mgr = processor.SchemaManager; IEnumerator se = catalog.EnumerateAxis(XdmAxis.Descendant, schemaNT); while (se.MoveNext()) { XdmNode schemaNode = (XdmNode)se.Current; log.WriteLine("Loading schema " + schemaNode.GetAttributeValue(fileNameAtt)); Uri location = new Uri(testSuiteDir + "/" + schemaNode.GetAttributeValue(fileNameAtt)); mgr.Compile(location); } total = 0; IEnumerator testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { total++; } // Process the test cases in turn testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { XdmNode testCase = (XdmNode)testCases.Current; String testName = testCase.GetAttributeValue(nameAtt); if (testPattern != null && !testName.StartsWith(testPattern)) { continue; } if (exceptions.ContainsKey(testName)) { continue; } log.WriteLine("Test " + testName); // Compile the query String errorCode = null; String filePath = testCase.GetAttributeValue(filePathAtt); XdmNode query = getChildElement(testCase, queryNT); String queryName = query.GetAttributeValue(nameAtt); String queryPath = testSuiteDir + "/Queries/XQuery/" + filePath + queryName + ".xq"; XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = new Uri(queryPath).ToString(); compiler.QueryResolver = new XqtsModuleResolver(testCase, findModule); compiler.SchemaAware = true; // Set all queries to schema-aware, because we don't really know whether they will have to handle typed input or not. ArrayList errors = new ArrayList(); compiler.ErrorList = errors; XQueryEvaluator xqe = null; FileStream stream = null; try { stream = new FileStream(queryPath, FileMode.Open, FileAccess.Read, FileShare.Read); xqe = compiler.Compile(stream).Load(); } catch (Exception e) { if (errors.Count > 0 && ((StaticError)errors[0]).ErrorCode != null) { errorCode = ((StaticError)errors[0]).ErrorCode.LocalName; } else if (e is StaticError && ((StaticError)e).ErrorCode != null) { log.WriteLine(e.Message); errorCode = ((StaticError)e).ErrorCode.LocalName; } else { log.WriteLine(e.Message); errorCode = "ErrorXXX"; } } finally { if (stream != null) { stream.Close(); } } // if the query compiled successfully, try to run it String outputPath = null; if (errorCode == null && xqe != null) { // Supply any input documents IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, inputFileNT); while (en.MoveNext()) { XdmNode file = (XdmNode)en.Current; String var = file.GetAttributeValue(variableAtt); if (var != null) { String sourceName = file.StringValue; XdmNode sourceDoc; if (sourceDocs.ContainsKey(sourceName)) { sourceDoc = (XdmNode)sourceDocs[sourceName]; } else { sourceDoc = buildSource(catalog, builder, sourceName); sourceDocs.Add(sourceName, sourceDoc); } xqe.SetExternalVariable(new QName("", var), sourceDoc); } } // Supply any input URIs IEnumerator eu = testCase.EnumerateAxis(XdmAxis.Child, inputUriNT); while (eu.MoveNext()) { XdmNode file = (XdmNode)eu.Current; String var = file.GetAttributeValue(variableAtt); if (var != null) { String sourceName = file.StringValue; if (sourceName.StartsWith("collection")) { // Supply a collection URI. // This seems to be the only way to distinguish a document URI // from a collection URI. String uri = "collection:" + sourceName; XPathSelector xpe = findCollection.Load(); xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName)); xpe.ContextItem = catalog; XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle(); if (collectionNode == null) { log.WriteLine("*** Collection " + sourceName + " not found"); } processor.RegisterCollection(new Uri(uri), getCollection(collectionNode)); xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri)); } else { // Supply a document URI. // We exploit the fact that the short name of the document is // always the same as the file name in these tests. With one exception! if (sourceName == "Char010D") { sourceName = "0x010D"; } String uri = "file:///" + testSuiteDir + "/TestSources/" + sourceName + ".xml"; xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri)); } } } // Supply the default collection if required XdmNode defaultCollection = getChildElement(testCase, defaultCollectionNT); if (defaultCollection != null) { String sourceName = defaultCollection.StringValue; XPathSelector xpe = findCollection.Load(); xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName)); xpe.ContextItem = catalog; XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle(); if (collectionNode == null) { log.WriteLine("*** Collection " + sourceName + " not found"); } processor.RegisterCollection(null, getCollection(collectionNode)); } // Supply any external variables defined as the result of a separate query IEnumerator ev = testCase.EnumerateAxis(XdmAxis.Child, inputQueryNT); while (ev.MoveNext()) { XdmNode inputQuery = (XdmNode)ev.Current; String fileName = inputQuery.GetAttributeValue(nameAtt); String subQueryPath = testSuiteDir + "/Queries/XQuery/" + filePath + fileName + ".xq"; XQueryCompiler subCompiler = processor.NewXQueryCompiler(); compiler.BaseUri = new Uri(subQueryPath).ToString(); FileStream subStream = new FileStream(subQueryPath, FileMode.Open, FileAccess.Read, FileShare.Read); XdmValue value = subCompiler.Compile(subStream).Load().Evaluate(); String var = inputQuery.GetAttributeValue(variableAtt); xqe.SetExternalVariable(new QName("", var), value); } // Supply the context item if required IEnumerator ci = testCase.EnumerateAxis(XdmAxis.Child, contextItemNT); while (ci.MoveNext()) { XdmNode file = (XdmNode)ci.Current; String sourceName = file.StringValue; if (!sourceDocs.ContainsKey(sourceName)) { XdmNode doc = buildSource(catalog, builder, sourceName); sourceDocs.Add(sourceName, doc); } XdmNode sourceDoc = (XdmNode)sourceDocs[sourceName]; xqe.ContextItem = sourceDoc; } // Create a serializer for the output outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out"; Serializer sr = new Serializer(); try { sr.SetOutputFile(outputPath); sr.SetOutputProperty(new QName("", "method"), "xml"); sr.SetOutputProperty(new QName("", "omit-xml-declaration"), "yes"); sr.SetOutputProperty(new QName("", "indent"), "no"); } catch (DynamicError) { // probably means that no output directory exists, which is probably because // an error is expected outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out"; sr.SetOutputFile(outputPath); } // Finally, run the query try { xqe.Run(sr); } catch (DynamicError e) { log.WriteLine(e.Message); QName code = e.ErrorCode; if (code != null && code.LocalName != null) { errorCode = code.LocalName; } else { errorCode = "ErrYYYYY"; } } catch (Exception e2) { log.WriteLine("Unexpected exception: " + e2.Message); log.WriteLine(e2.StackTrace); errorCode = "CRASH!!!"; } } // Compare actual results with expected results if (errorCode != null) { // query returned an error at compile time or run-time, check this was expected string expectedError = ""; bool matched = false; IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT); while (en.MoveNext()) { XdmNode error = (XdmNode)en.Current; String expectedErrorCode = error.StringValue; expectedError += (expectedErrorCode + " "); if (expectedErrorCode.Equals(errorCode)) { matched = true; feedback.Feedback(passed++, failed, total); log.WriteLine("Error " + errorCode + " as expected"); results.WriteLine("<test-case name='" + testName + "' result='pass'/>"); break; } } if (!matched) { if (expectedError.Equals("")) { feedback.Feedback(passed, failed++, total); log.WriteLine("Error " + errorCode + ", expected success"); results.WriteLine("<test-case name='" + testName + "' result='fail' comment='error " + errorCode + ", expected success'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } else { feedback.Feedback(passed++, failed, total); log.WriteLine("Error " + errorCode + ", expected " + expectedError); results.WriteLine("<test-case name='" + testName + "' result='pass' comment='error " + errorCode + ", expected " + expectedError + "'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } } } else { // query returned no error bool matched = false; String diag = ""; IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, outputFileNT); while (en.MoveNext()) { XdmNode outputFile = (XdmNode)en.Current; String fileName = testSuiteDir + "/ExpectedTestResults/" + filePath + outputFile.StringValue; String comparator = outputFile.GetAttributeValue(compareAtt); if (comparator.Equals("Inspect")) { matched = true; feedback.Feedback(passed++, failed, total); results.WriteLine("<test-case name='" + testName + "' result='inspect'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); break; } else { String comparison = fileComparer.compare(outputPath, fileName, comparator); matched = (comparison == "OK" || comparison.StartsWith("#")); if (matched) { feedback.Feedback(passed++, failed, total); results.WriteLine("<test-case name='" + testName + "' result='pass'/>"); diag = diag + ("<!-- " + comparison + " -->\n"); break; } } } if (!matched) { string expectedError = ""; IEnumerator ee = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT); while (ee.MoveNext()) { XdmNode error = (XdmNode)ee.Current; String expectedErrorCode = error.StringValue; expectedError += (expectedErrorCode + " "); } if (expectedError.Equals("")) { feedback.Feedback(passed, failed++, total); log.WriteLine("Results differ from expected results"); results.WriteLine("<test-case name='" + testName + "' result='fail'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } else { feedback.Feedback(passed, failed++, total); log.WriteLine("Error " + expectedError + "expected but not reported"); results.WriteLine("<test-case name='" + testName + "' result='fail' comment='expected error " + expectedError + "not reported'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } } } } results.WriteLine("</test-suite-result>"); results.Close(); log.Close(); }
/// <summary> /// Show a query producing a document as its result and serializing this to a FileStream /// </summary> public override void run(Uri samplesDir) { Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = samplesDir.ToString(); compiler.DeclareNamespace("saxon", "http://saxon.sf.net/"); XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>"); XQueryEvaluator eval = exp.Load(); Serializer qout = new Serializer(); qout.SetOutputProperty(Serializer.METHOD, "xml"); qout.SetOutputProperty(Serializer.INDENT, "yes"); qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1"); qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write)); Console.WriteLine("Output written to testoutput.xml"); eval.Run(qout); }
/// <summary> /// Show a query reading an input document using an XmlReader (the .NET XML parser) /// </summary> public override void run(Uri samplesDir) { Processor processor = new Processor(); String inputFileName = new Uri(samplesDir, "data/books.xml").ToString(); XmlTextReader reader = new XmlTextReader(inputFileName, UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml"))); //new FileStream(inputFileName, FileMode.Open, FileAccess.Read)); reader.Normalization = true; // add a validating reader - not to perform validation, but to expand entity references XmlValidatingReader validator = new XmlValidatingReader(reader); validator.ValidationType = ValidationType.None; XdmNode doc = processor.NewDocumentBuilder().Build(validator); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile("/"); XQueryEvaluator eval = exp.Load(); eval.ContextItem = doc; Serializer qout = new Serializer(); qout.SetOutputProperty(Serializer.METHOD, "xml"); qout.SetOutputProperty(Serializer.INDENT, "yes"); qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write)); eval.Run(qout); }
/// <summary> /// Run an XSLT transformation setting serialization properties from the calling application /// </summary> public override void run(Uri samplesDir) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml")); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load(); // 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.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "no"); serializer.SetOutputWriter(Console.Out); // Transform the source XML and serialize the result document transformer.Run(serializer); }
/// <summary> /// Show a transformation using calls to extension functions /// </summary> public override void run(Uri samplesDir) { // 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 = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + @" xmlns:math='http://example.math.co.uk/demo'> " + @" <xsl:template name='go'> " + @" <out sqrt2='{math:sqrt(2.0e0)}' " + @" sqrtEmpty='{math:sqrt(())}'/> " + @" </xsl:template></xsl:transform>"; // Register the integrated extension function math:sqrt processor.RegisterExtensionFunction(new Sqrt()); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load(); // Set the root node of the source document to be the initial context node transformer.InitialTemplate = new QName("go"); // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); serializer.SetOutputProperty(Serializer.INDENT, "yes"); // Transform the source XML to System.out. transformer.Run(serializer); }
/// <summary> /// Demonstrate XSLT extensibility using user-written extension functions /// </summary> /// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesPE, use /// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE /// </remarks> public override void run(Uri samplesDir) { // 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 = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" + @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=ExamplesPE' " + @" xmlns:tz='clitype:System.TimeZone' " + @" xmlns:math='http://example.math.co.uk/demo' " + @" xmlns:env='http://example.env.co.uk/demo' " + @" exclude-result-prefixes='ext math env tz'> " + @" <xsl:param name='timezone' required='yes'/> " + @" <xsl:template match='/'> " + @" <out addition='{ext:add(2,2)}' " + @" average='{ext:average((1,2,3,4,5,6))}' " + @" firstchild='{ext:nameOfFirstChild(.)}' " + @" timezone='{tz:StandardName($timezone)}' " + @" sqrt2='{math:sqrt(2.0e0)}' " + @" defaultNamespace='{env:defaultNamespace()}' " + @" sqrtEmpty='{math:sqrt(())}'> " + @" <xsl:copy-of select='ext:FirstChild((//ITEM)[1])'/> " + @" <defaultNS value='{env:defaultNamespace()}' xsl:xpath-default-namespace='http://default.namespace.com/' /> " + @" <combine1><xsl:sequence select='ext:combine(ext:FirstChild((//ITEM)[1]), count(*))'/></combine1> " + @" <combine2><xsl:sequence select='ext:combine((//TITLE)[1], (//AUTHOR)[1])'/></combine2> " + @" </out> " + @" </xsl:template></xsl:transform>"; // Register the integrated extension functions math:sqrt and env:defaultNamespace processor.RegisterExtensionFunction(new Sqrt()); processor.RegisterExtensionFunction(new DefaultNamespace()); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load(); // Load the source document (must be a wrapper around an XmlDocument for this test) XmlDocument doc = new XmlDocument(); doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/books.xml")); XdmNode input = processor.NewDocumentBuilder().Wrap(doc); // Set the root node of the source document to be the initial context node transformer.InitialContextNode = input; // Supply a parameter transformer.SetParameter(new QName("", "timezone"), XdmAtomicValue.WrapExternalObject(TimeZone.CurrentTimeZone)); // Create a serializer Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); serializer.SetOutputProperty(Serializer.INDENT, "yes"); // Transform the source XML to System.out. transformer.Run(serializer); }
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; }
/// <summary> /// Demonstrate XQuery Update /// </summary> public override void run(Uri samplesDir) { Processor processor = new Processor(true); DocumentBuilder loader = processor.NewDocumentBuilder(); loader.BaseUri = new Uri(samplesDir, "data/books.xml"); loader.TreeModel = TreeModel.LinkedTree; XdmNode indoc = loader.Build(new Uri(samplesDir, "data/books.xml")); Console.Out.WriteLine("=========== BEFORE UPDATE ==========="); Serializer serializer0 = new Serializer(); serializer0.SetOutputProperty(Serializer.METHOD, "xml"); serializer0.SetOutputProperty(Serializer.INDENT, "yes"); serializer0.SetOutputWriter(Console.Out); processor.WriteXdmValue(indoc, serializer0); String query = "for $i in //PRICE return \n" + "replace value of node $i with $i - 0.05"; XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.UpdatingEnabled = true; XQueryExecutable exp = compiler.Compile(query); XQueryEvaluator eval = exp.Load(); eval.ContextItem = indoc; XdmNode[] updatedNodes = eval.RunUpdate(); foreach (XdmNode root in updatedNodes) { Uri documentUri = root.DocumentUri; if (documentUri != null && documentUri.Scheme == "file") { Stream stream = UriConnection.getWritableUriStream(documentUri); Serializer serializer = new Serializer(); serializer.SetOutputProperty(Serializer.METHOD, "xml"); serializer.SetOutputProperty(Serializer.INDENT, "yes"); serializer.SetOutputStream(stream); processor.WriteXdmValue(root, serializer); } } Console.Out.WriteLine("=========== AFTER UPDATE ==========="); processor.WriteXdmValue(indoc, serializer0); }