public override IXPathNavigable Run(XsltRuntimeOptions options) { XdmDestination xdmDest = new XdmDestination(); Run(xdmDest, options); return xdmDest.XdmNode.ToXPathNavigable(); }
/** * Construct an Environment * * @param xpc the XPathCompiler used to process the catalog file * @param env the Environment element in the catalog file * @param environments the set of environments to which this one should be added (may be null) * @return the constructed Environment object * @throws SaxonApiException */ private TestEnvironment processEnvironment(XPathCompiler xpc, XdmItem env, Dictionary<string, TestEnvironment> environments) { TestEnvironment environment = new TestEnvironment(); string name = ((XdmNode)env).GetAttributeValue(new QName("name")); environment.processor = new Processor(true); XmlUrlResolver res = new XmlUrlResolver(); if (generateByteCode == 1) { environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true"); environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false"); } else if (generateByteCode == 2) { environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true"); environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true"); } else { environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false"); environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false"); } environment.xpathCompiler = environment.processor.NewXPathCompiler(); environment.xpathCompiler.BaseUri = (((XdmNode)env).BaseUri).ToString(); environment.xqueryCompiler = environment.processor.NewXQueryCompiler(); environment.xqueryCompiler.BaseUri = (((XdmNode)env).BaseUri).ToString(); if (unfolded) { //environment.xqueryCompiler.getUnderlyingStaticContext().setCodeInjector(new LazyLiteralInjector()); } DocumentBuilder builder = environment.processor.NewDocumentBuilder(); environment.sourceDocs = new Dictionary<string, XdmNode>(); if (environments != null && name != null) { try { environments.Add(name, environment); }catch(Exception e){} } System.Collections.IEnumerator dependency = xpc.Evaluate("dependency", env).GetEnumerator(); while (dependency.MoveNext()) { if (!DependencyIsSatisfied((XdmNode)dependency.Current, environment)) { environment.usable = false; } } // set the base Uri if specified IEnumerator base1 = xpc.Evaluate("static-base-uri", env).GetEnumerator(); while (base1.MoveNext()) { string Uri = ((XdmNode)base1.Current).GetAttributeValue(new QName("uri")); try { environment.xpathCompiler.BaseUri = Uri; environment.xqueryCompiler.BaseUri = Uri; } catch (Exception e) { Console.WriteLine("**** invalid base Uri " + Uri); } } // set any requested collations base1 = xpc.Evaluate("collation", env).GetEnumerator(); while (base1.MoveNext()) { string uriStr = ((XdmNode)base1.Current).GetAttributeValue(new QName("uri")); string defaultAtt = ((XdmNode)base1.Current).GetAttributeValue(new QName("default")); Boolean defaultCol = false; if (defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1"))) { defaultCol = true; } if (uriStr.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind")) { net.sf.saxon.Configuration config = xpc.Processor.Implementation; net.sf.saxon.lib.StringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config); CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo; CompareOptions options = CompareOptions.IgnoreCase; environment.xpathCompiler.DeclareCollation(new Uri(uriStr), compareInfo, options, defaultCol); environment.xqueryCompiler.DeclareCollation(new Uri(uriStr), compareInfo, options, defaultCol); } } // declare the requested namespaces IEnumerator nsElement = xpc.Evaluate("namespace", env).GetEnumerator(); while (nsElement.MoveNext()) { string prefix = ((XdmNode)nsElement.Current).GetAttributeValue(new QName("prefix")); string uri = ((XdmNode)nsElement.Current).GetAttributeValue(new QName("uri")); environment.xpathCompiler.DeclareNamespace(prefix, uri); environment.xqueryCompiler.DeclareNamespace(prefix, uri); } // load the requested schema documents SchemaManager manager = environment.processor.SchemaManager; System.Collections.IEnumerator schema = xpc.Evaluate("schema", env).GetEnumerator(); while (schema.MoveNext()) { string href = ((XdmNode)schema.Current).GetAttributeValue(new QName("file")); manager.Compile((new Uri(((XdmNode)env).BaseUri, href))); } // load the requested source documents //IEnumerator source = xpc.Evaluate("source", env).GetEnumerator(); foreach (XdmItem source in xpc.Evaluate("source", env)) { Uri href = res.ResolveUri(((XdmNode)env).BaseUri, ((XdmNode)source).GetAttributeValue(new QName("file"))); string Uri = ((XdmNode)source).GetAttributeValue(new QName("uri")); string validation = ((XdmNode)source).GetAttributeValue(new QName("", "validation")); XdmNode doc = null; if (validation == null || validation.Equals("skip")) { try { doc = builder.Build(href); } catch (Exception e) { feedback.Message("Error:" + e.Message+" *** failed to build source document " + href, false); } } else { try { SchemaValidator validator = manager.NewSchemaValidator(); XdmDestination xdmDest = new XdmDestination(); validator.IsLax = validation.Equals("lax"); validator.SetDestination(xdmDest); validator.SetSource(href); validator.Run(); doc = xdmDest.XdmNode; environment.xpathCompiler.SchemaAware = true; environment.xqueryCompiler.SchemaAware = true; } catch(Exception e) { feedback.Message("Error:" + e.Message+" *** failed to build source document " + href, false); } } if (Uri != null) { environment.sourceDocs.Add(Uri, doc); } string role = ((XdmNode)source).GetAttributeValue(new QName("role")); if (role != null) { if (".".Equals(role)) { environment.contextNode = doc; } else if (role.StartsWith("$")) { string varName = role.Substring(1); environment.params1.Add(new QName(varName), doc); environment.xpathCompiler.DeclareVariable(new QName(varName)); environment.paramDeclarations.Append("declare variable $" + varName + " external; "); } } } // create a collection Uri resolved to handle the requested collections Hashtable collections = new Hashtable(); foreach (XdmItem coll in xpc.Evaluate("collection", env)) { string collectionUri = ((XdmNode)coll).GetAttributeValue(new QName("uri")); if (collectionUri == null || collectionUri.Equals("")) { collectionUri = "http://www.saxonica.com/defaultCollection"; } IList<Uri> docs = new List<Uri>(); foreach (XdmItem source in xpc.Evaluate("source", coll)) { Uri href = res.ResolveUri(((XdmNode)env).BaseUri, ((XdmNode)source).GetAttributeValue(new QName("file"))); //File file = new File((((XdmNode) env).GetBaseUri().resolve(href))); string id = ((XdmNode)source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id")); XdmNode doc = builder.Build(href); if (id != null) { environment.sourceDocs.Add(id, doc); } environment.processor.RegisterCollection(href, getCollection(doc, href.AbsoluteUri)); environment.sourceDocs.Add(href.ToString(), doc); docs.Add(doc.DocumentUri); } try { collections.Add(new Uri(collectionUri), docs); } catch (Exception e) { feedback.Message("**** Invalid collection Uri " + collectionUri, false); } } if (collections.Count != 0) { environment.processor.Implementation.setCollectionURIResolver(new CollectionResolver(collections)); /* new net.sf.saxon.lib.CollectionURIResolver() { public SequenceIterator resolve(string href, string base, XPathContext context) { try { List<AnyUriValue> docs; if (href == null) { docs = collections.get(new Uri("")); } else { Uri abs = new Uri(base).resolve(href); docs = collections.get(abs); } if (docs == null) { return EmptyIterator.getInstance(); } else { return new ListIterator(docs); } } catch (UriSyntaxException e) { Console.WriteLine("** Invalid Uri: " + e.Message); return EmptyIterator.getInstance(); } } } )*/ } // register any required decimal formats IEnumerator decimalFormat = xpc.Evaluate("decimal-format", env).GetEnumerator(); while (decimalFormat.MoveNext()) { XdmNode formatElement = (XdmNode) decimalFormat.Current; string formatName = formatElement.GetAttributeValue(new QName("name")); QName formatQName = null; if (formatName != null) { if (formatName.IndexOf(':') < 0) { formatQName = new QName("", "", formatName); } else { try { formatQName = new QName(environment.xpathCompiler.GetNamespaceURI(formatName, false), formatName.Substring(formatName.IndexOf(':')+1)); } catch (Exception) { feedback.Message("**** Invalid QName as decimal-format name", false); formatQName = new QName("", "", "error-name"); } } environment.paramDecimalDeclarations.Append("declare decimal-format " + formatName + " "); } else { environment.paramDecimalDeclarations.Append("declare default decimal-format "); } foreach (XdmItem decimalFormatAtt in xpc.Evaluate("@* except @name", formatElement)) { XdmNode formatAttribute = (XdmNode) decimalFormatAtt; string property = formatAttribute.NodeName.LocalName; string value = formatAttribute.StringValue; environment.paramDecimalDeclarations.Append(property + "=\"" + value + "\" "); environment.xpathCompiler.SetDecimalFormatProperty(formatQName, property, value); } environment.paramDecimalDeclarations.Append(";"); } // declare any variables IEnumerator param = xpc.Evaluate("param", env).GetEnumerator(); while (param.MoveNext()) { string varName = ((XdmNode)param.Current).GetAttributeValue(new QName("name")); XdmValue value = null; string sourceStr = ((XdmNode)param.Current).GetAttributeValue(new QName("source")); if (sourceStr != null) { XdmNode sourceDoc = (XdmNode)(environment.sourceDocs[sourceStr]); if (sourceDoc == null) { Console.WriteLine("**** Unknown source document " + sourceDoc.ToString()); } value = sourceDoc; } else { string select = ((XdmNode)param.Current).GetAttributeValue(new QName("select")); value = xpc.Evaluate(select, null); } environment.params1.Add(new QName(varName), value); environment.xpathCompiler.DeclareVariable(new QName(varName)); string declared = ((XdmNode)param.Current).GetAttributeValue(new QName("declared")); if (declared != null && "true".Equals(declared) || "1".Equals(declared)) { // no action } else { environment.paramDeclarations.Append("declare variable $" + varName + " external; "); } } return environment; }
/// <summary> /// Transform from an XDM tree to an XDM tree /// </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 compiler XsltCompiler compiler = processor.NewXsltCompiler(); // Compile the stylesheet XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).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. }
/// <summary> /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output /// </summary> public override void run(Uri samplesDir) { Processor processor = new Processor(); DocumentBuilder loader = processor.NewDocumentBuilder(); loader.BaseUri = new Uri(samplesDir, "data/books.xml"); XdmNode indoc = loader.Build(loader.BaseUri); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>"); XQueryEvaluator eval = exp.Load(); eval.ContextItem = indoc; XdmDestination qout = new XdmDestination(); eval.Run(qout); XdmNode outdoc = qout.XdmNode; Console.WriteLine(outdoc.OuterXml); }
/// <summary> /// Show a transformation using a registered collection /// </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/othello.xml")); // Define a stylesheet that splits the document up String stylesheet = "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" + "<xsl:template name='main'>\n" + " <out>\n" + " <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" + " <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" + " </xsl:for-each><zzz/>\n" + " <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" + " <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" + " </xsl:for-each>\n" + " </out>\n" + "</xsl:template>\n" + "</xsl:stylesheet>"; Uri[] documentList = new Uri[2]; documentList[0] = new Uri(samplesDir, "data/othello.xml"); documentList[1] = new Uri(samplesDir, "data/books.xml"); processor.RegisterCollection(new Uri("http://www.example.org/my-collection"), documentList); XsltCompiler compiler = processor.NewXsltCompiler(); compiler.BaseUri = new Uri("http://localhost/stylesheet"); XsltExecutable exec = compiler.Compile(new StringReader(stylesheet)); // Create a transformer for the stylesheet. XsltTransformer transformer = exec.Load(); // Set the root node of the source document to be the initial context node transformer.InitialTemplate = new QName("", "main"); //Set the destination XdmDestination results = new XdmDestination(); // Transform the XML transformer.Run(results); // Show the result Console.WriteLine(results.XdmNode.ToString()); }
/// <summary> /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node /// </summary> /// <param name="fileNames"> /// 1. The source document /// 2. The stylesheet /// </param> 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/othello.xml")); // Navigate to the first grandchild XPathSelector eval = processor.NewXPathCompiler().Compile("/PLAY/FM[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(samplesDir, "styles/summarize.xsl")).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); }
/// <summary> /// Show that the XsltTransformer is serially reusable (we run it twice with different parameter settings) /// </summary> public override void run(Uri samplesDir) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document, building a tree XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml")); // Compile the stylesheet XsltExecutable exec = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/summarize.xsl")); // Create a transformer XsltTransformer transformer = exec.Load(); // Run it once transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false)); transformer.InitialContextNode = input; XdmDestination results = new XdmDestination(); transformer.Run(results); Console.WriteLine("1: " + results.XdmNode.OuterXml); // Run it again transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(true)); transformer.InitialContextNode = input; results.Reset(); transformer.Run(results); Console.WriteLine("2: " + results.XdmNode.OuterXml); }
/// <summary> /// Run an XSLT transformation using the id() function, with DTD validation /// </summary> public override void run(Uri samplesDir) { // Create a Processor instance Processor processor = new Processor(); // Load the source document. The Microsoft .NET parser does not report attributes of type ID. The only // way to use the function is therefore (a) to use a different parser, or (b) to use xml:id instead. We // choose the latter course. String doc = "<!DOCTYPE table [" + "<!ELEMENT table (row*)>" + "<!ELEMENT row EMPTY>" + "<!ATTLIST row xml:id ID #REQUIRED>" + "<!ATTLIST row value CDATA #REQUIRED>]>" + "<table><row xml:id='A123' value='green'/><row xml:id='Z789' value='blue'/></table>"; DocumentBuilder builder = processor.NewDocumentBuilder(); builder.DtdValidation = true; builder.BaseUri = samplesDir; MemoryStream ms = new MemoryStream(); StreamWriter tw = new StreamWriter(ms); tw.Write(doc); tw.Flush(); Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length); XdmNode input = builder.Build(instr); // Define a stylesheet that uses the id() function String stylesheet = "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" + "<xsl:template match='/'>\n" + " <xsl:copy-of select=\"id('Z789')\"/>\n" + "</xsl:template>\n" + "</xsl:stylesheet>"; XsltCompiler compiler = processor.NewXsltCompiler(); compiler.BaseUri = new Uri("http://localhost/stylesheet"); XsltExecutable exec = compiler.Compile(new StringReader(stylesheet)); //Create a transformer for the stylesheet XsltTransformer transformer = exec.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(); // Transform the XML transformer.Run(results); // Show the result Console.WriteLine(results.XdmNode.ToString()); }
/// <summary> /// Run a transformation driven by an xml-stylesheet processing instruction in the source document /// </summary> /// <param name="fileNames"> /// 1. The source document /// </param> public override void run(Uri samplesDir) { // Create a Processor instance. Processor processor = new Processor(); XsltExecutable exec; // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml")); //Console.WriteLine("=============== source document ==============="); //Console.WriteLine(input.OuterXml); //Console.WriteLine("=========== end of source document ============"); // Navigate to the xml-stylesheet processing instruction having the pseudo-attribute type=text/xsl; // then extract the value of the href pseudo-attribute if present String path = @"/processing-instruction(xml-stylesheet)[matches(.,'type\s*=\s*[''""]text/xsl[''""]')]" + @"/replace(., '.*?href\s*=\s*[''""](.*?)[''""].*', '$1')"; XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load(); eval.ContextItem = input; XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle(); String href = (hrefval == null ? null : hrefval.ToString()); if (href == null || href == "") { Console.WriteLine("No suitable xml-stylesheet processing instruction found"); return; } else if (href[0] == '#') { // The stylesheet is embedded in the source document and identified by a URI of the form "#id" Console.WriteLine("Locating embedded stylesheet with href = " + href); String idpath = "id('" + href.Substring(1) + "')"; eval = processor.NewXPathCompiler().Compile(idpath).Load(); eval.ContextItem = input; XdmNode node = (XdmNode)eval.EvaluateSingle(); if (node == null) { Console.WriteLine("No element found with ID " + href.Substring(1)); return; } exec = processor.NewXsltCompiler().Compile(node); } else { // The stylesheet is in an external document Console.WriteLine("Locating stylesheet at uri = " + new Uri(input.BaseUri, href)); // Fetch and compile the referenced stylesheet exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString())); } // Create a transformer XsltTransformer transformer = exec.Load(); // Run it transformer.InitialContextNode = input; XdmDestination results = new XdmDestination(); transformer.Run(results); Console.WriteLine("1: " + results.XdmNode.OuterXml); }
/// <summary> /// Run the test /// </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 compiler XsltCompiler compiler = processor.NewXsltCompiler(); // Compile all three stylesheets XsltTransformer transformer1 = compiler.Compile(new Uri(samplesDir, "styles/identity.xsl")).Load(); XsltTransformer transformer2 = compiler.Compile(new Uri(samplesDir, "styles/books.xsl")).Load(); XsltTransformer transformer3 = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load(); // Now run them in series transformer1.InitialContextNode = input; XdmDestination results1 = new XdmDestination(); transformer1.Run(results1); //Console.WriteLine("After phase 1:"); //Console.WriteLine(results1.XdmNode.OuterXml); transformer2.InitialContextNode = results1.XdmNode; XdmDestination results2 = new XdmDestination(); transformer2.Run(results2); //Console.WriteLine("After phase 2:"); //Console.WriteLine(results2.XdmNode.OuterXml); transformer3.InitialContextNode = results2.XdmNode; //TextWriterDestination results3 = new TextWriterDestination(new XmlTextWriter(Console.Out)); XdmDestination results3 = new XdmDestination(); transformer3.Run(results3); Console.WriteLine("After phase 3:"); Console.WriteLine(results3.XdmNode.OuterXml); }
/** * Method main. First argument is the Saxon samples directory. */ public static void Main(String[] argv) { String samplesDir; if (argv.Length > 0) { samplesDir = argv[0]; } else { String home = Environment.GetEnvironmentVariable("SAXON_HOME"); if (home == null) { Console.WriteLine("No input directory supplied, and SAXON_HOME is not set"); return; } else { if (home.EndsWith("/") || home.EndsWith("\\")) { samplesDir = home + "samples/"; } else { samplesDir = home + "/samples/"; } } } UriBuilder ub = new UriBuilder(); ub.Scheme = "file"; ub.Host = ""; ub.Path = samplesDir; Uri baseUri = ub.Uri; Console.WriteLine("Base URI: " + baseUri.ToString()); // Create a schema-aware Processor Processor saxon = new Processor(true); // Load a schema SchemaManager manager = saxon.SchemaManager; manager.ErrorList = new ArrayList(); Uri schemaUri = new Uri(baseUri, "data/books.xsd"); try { manager.Compile(schemaUri); } catch (Exception e) { Console.WriteLine("Schema compilation failed with " + manager.ErrorList.Count + " errors"); foreach (StaticError error in manager.ErrorList) { Console.WriteLine("At line " + error.LineNumber + ": " + error.Message); } return; } // Use this to validate an instance document SchemaValidator validator = manager.NewSchemaValidator(); Uri instanceUri = new Uri(baseUri, "data/books.xml"); validator.SetSource(instanceUri); validator.ErrorList = new ArrayList(); XdmDestination psvi = new XdmDestination(); validator.SetDestination(psvi); try { validator.Run(); } catch (Exception e) { Console.WriteLine("Instance validation failed with " + validator.ErrorList.Count + " errors"); foreach (StaticError error in validator.ErrorList) { Console.WriteLine("At line " + error.LineNumber + ": " + error.Message); } } // Run a query on the result to check that it has type annotations XQueryCompiler xq = saxon.NewXQueryCompiler(); XQueryEvaluator xv = xq.Compile("data((//PRICE)[1]) instance of xs:decimal").Load(); xv.ContextItem = psvi.XdmNode; Console.WriteLine("Price is decimal? " + xv.EvaluateSingle().ToString()); }
/// <summary> /// Show validation of an instance document against a schema /// </summary> public override void run(Uri samplesDir) { // Load a schema Processor processor; try { processor = new Processor(true); } catch (Exception err) { Console.WriteLine(err); Console.WriteLine("Failed to load Saxon-EE (use -HE option to run Saxon-HE tests only)"); return; } processor.SetProperty("http://saxon.sf.net/feature/timing", "true"); processor.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true"); SchemaManager manager = processor.SchemaManager; manager.XsdVersion = "1.1"; manager.ErrorList = new ArrayList(); Uri schemaUri = new Uri(samplesDir, "data/books.xsd"); try { manager.Compile(schemaUri); } catch (Exception e) { Console.WriteLine(e); Console.WriteLine("Schema compilation failed with " + manager.ErrorList.Count + " errors"); foreach (StaticError error in manager.ErrorList) { Console.WriteLine("At line " + error.LineNumber + ": " + error.Message); } return; } // Use this to validate an instance document SchemaValidator validator = manager.NewSchemaValidator(); //Uri instanceUri = new Uri(samplesDir, "data/books-invalid.xml"); //validator.SetSource(instanceUri); XmlReader xmlReader = XmlReader.Create(samplesDir + "data/books-invalid.xml"); validator.SetSource(xmlReader); validator.ErrorList = new ArrayList(); XdmDestination psvi = new XdmDestination(); validator.SetDestination(psvi); try { validator.Run(); } catch (Exception e) { Console.WriteLine(e); Console.WriteLine("Instance validation failed with " + validator.ErrorList.Count + " errors"); foreach (StaticError error in validator.ErrorList) { Console.WriteLine("At line " + error.LineNumber + ": " + error.Message); } return; } // Run a query on the result to check that it has type annotations XQueryCompiler xq = processor.NewXQueryCompiler(); XQueryEvaluator xv = xq.Compile("data((//PRICE)[1]) instance of xs:decimal").Load(); xv.ContextItem = psvi.XdmNode; Console.WriteLine("Price is decimal? " + xv.EvaluateSingle().ToString()); }
/// <summary> /// The Saxon xslt2.0 transformer method /// </summary> /// <param name="xslFile">The xslt file you want to transform with</param> /// <param name="xml">The xml you want to transform against</param> /// <param name="numberOfErrors">The number of errors encounted</param> /// <returns>A report of how the transform went</returns> private string TransformUsingXslt2(string xslFile, string xml, ref int numberOfErrors) { List<StaticError> errors = new List<StaticError>(); try { Processor processor = new Processor(); DocumentBuilder xmlDoc = processor.NewDocumentBuilder(); XmlDocument testXML = new XmlDocument(); testXML.LoadXml(xml); XdmNode xmlBaseNode = xmlDoc.Build(testXML.FirstChild); XsltTransformer transformer = null; if (_cachedSaxonXslt.ContainsKey(xslFile)) { transformer = _cachedSaxonXslt[xslFile]; } else { DocumentBuilder xsltDoc = processor.NewDocumentBuilder(); XdmNode xsltBaseNode = xsltDoc.Build(new Uri(xslFile)); XsltCompiler compiler = processor.NewXsltCompiler(); compiler.ErrorList = errors; XsltExecutable executable = compiler.Compile(xsltBaseNode); transformer = executable.Load(); } transformer.InitialContextNode = xmlBaseNode; XdmDestination output = new XdmDestination(); transformer.Run(output); _cachedSaxonXslt.Add(xslFile, transformer); } catch (Exception ex) { string errorMsg = ex.Message; if (ex.InnerException != null) { errorMsg += " " + ex.InnerException.Message; } numberOfErrors++; foreach (StaticError error in errors) { errorMsg += "\n\r" + error.Message + "\n\r" + error.ModuleUri + "\n\r"; numberOfErrors++; } return errorMsg; } return "Transform completed without errors."; }