public NodeSet() { this._FunctionName = new QName("http://exslt.org/common", "node-set"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAnyNodeType.Instance, '*') }; }
public AppSettings() { this._FunctionName = new QName(UtilModule.Namespace, "app-settings"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' ') }; this.resultType = new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '*'); }
public SetContentType() { this._FunctionName = new QName(ResponseModule.Namespace, "set-content-type"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '), }; this.resultType = new XdmSequenceType(XdmAnyItemType.Instance, '?'); }
public AbsolutePath() { this._FunctionName = new QName(UtilModule.Namespace, "absolute-path"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' ') }; this.resultType = new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '); }
public QueryString() { this._FunctionName = new QName(RequestModule.Namespace, "query-string"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '), }; this.resultType = new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '*'); }
public ReferrerUrlComponents() { this._FunctionName = new QName(RequestModule.Namespace, "referrer-url-components"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '), new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' ') }; this.resultType = new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?'); }
public Send(SaxonItemFactory itemFactory) { this.itemFactory = itemFactory; this._FunctionName = new QName(XPathSmtpClient.Namespace, "send"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmNodeKind.Element, ' ') }; this.resultType = new XdmSequenceType(XdmNodeKind.Element, ' '); }
public void AddParameter(string name, [NotNull] string value) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Argument is null or whitespace", nameof(name)); if (value == null) throw new ArgumentNullException(nameof(value)); var key = new QName(name); _externalParameters[key] = new XdmAtomicValue(value); }
public Set() { this._FunctionName = new QName(SessionModule.Namespace, "set"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '), new XdmSequenceType(XdmAnyItemType.Instance, ' '), }; this.resultType = new XdmSequenceType(XdmAnyItemType.Instance, '?'); }
public SendRequest(SaxonItemFactory itemFactory) { this.itemFactory = itemFactory; this._FunctionName = new QName(XPathHttpClient.Namespace, "send-request"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmNodeKind.Element, '?'), new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?'), new XdmSequenceType(XdmAnyItemType.Instance, '*') }; this.resultType = new XdmSequenceType(XdmAnyItemType.Instance, '+'); }
public ValidateWithSchematron(SaxonItemFactory itemFactory) { this.itemFactory = itemFactory; this._FunctionName = new QName(ValidationModule.Namespace, "validate-with-schematron"); this._ArgumentTypes = new[] { new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '), new XdmSequenceType(XdmAnyNodeType.Instance, ' '), new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), '?'), new XdmSequenceType(XdmAnyNodeType.Instance, '*'), }; this.resultType = new XdmSequenceType(XdmNodeKind.Document, ' '); }
static void Main(string[] args) { string infile = @"c:\daisybooks\verysimplebook\verysimplebook.xml"; string infile_dir = @"c:\daisybooks\verysimplebook\"; string xsltfile = @"c:\devel\amis\trunk\amis\bin\xslt\dtbook\dtbook2xhtml.xsl"; string outfile = @"c:\devel\amis\sandbox\dtbooktransformer_out.xml"; // Create a Processor instance. Processor processor = new Processor(); // Load the source document XdmNode input = processor.NewDocumentBuilder().Build(new Uri(infile)); // Create a transformer for the stylesheet. XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltfile)).Load(); QName basedir = new QName("", "baseDir"); List<XdmAtomicValue> elementNames = new List<XdmAtomicValue>(); elementNames.Add(new XdmAtomicValue(infile_dir)); XdmValue basedir_value = new XdmValue(elementNames); transformer.SetParameter(basedir, basedir_value); // Set the user-written XmlResolver UserXmlResolver runTimeResolver = new UserXmlResolver(); runTimeResolver.Message = "** Calling transformation-time XmlResolver: "; transformer.InputXmlResolver = runTimeResolver; // Set the root node of the source document to be the initial context node transformer.InitialContextNode = input; /* * String outfile = "OutputFromXsltSimple2.xml"; Serializer serializer = new Serializer(); serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write)); */ // Create a serializer, with output to the standard output stream Serializer serializer = new Serializer(); serializer.SetOutputWriter(Console.Out); // Transform the source XML and serialize the result document transformer.Run(serializer); Console.ReadLine(); }
/// <summary> /// Add parameters to a transform /// </summary> /// <param name="parameterList"></param> /// <param name="xslProc"></param> private void AddParameters(XMLUtilities.XSLParameter[] parameterList) { if (parameterList != null) { foreach (XMLUtilities.XSLParameter rParam in parameterList) { var parameterName = new QName(rParam.Name); // Following is a specially recognized parameter name if (rParam.Name == "prmSDateTime") { var parameterValue = new XdmAtomicValue((new QName(XMLUtilities.GetCurrentDateTime(CultureToUse)))); m_transformer.SetParameter(parameterName, parameterValue); } else { var parameterValue = new XdmAtomicValue((new QName(rParam.Value))); m_transformer.SetParameter(parameterName, parameterValue); } } } }
/** * This class serves as a variable resolver. The only variable used is $word. * @param qName the name of the variable required * @return the current value of the variable */ public Object resolveVariable(QName qName) { if (qName.LocalName == "word") { return currentWord; } else { return null; } }
/// <summary> /// Set the value of an external variable declared in the query. /// </summary> /// <param name="name">The name of the external variable, expressed /// as a <c>QName</c>. If an external variable of this name has been declared in the /// query prolog, the given value will be assigned to the variable. If the /// variable has not been declared, calling this method has no effect (it is /// not an error).</param> /// <param name="value">The value to be given to the external variable. /// If the variable declaration defines a required type for the variable, then /// this value must match the required type: no conversions are applied.</param> public void SetExternalVariable(QName name, XdmValue value) { evaluator.setExternalVariable(new JXQName(name.ToStructuredQName()), value == null ? null : XdmValue.FromGroundedValueToJXdmValue(value.value)); }
/** * Run the tests * @param args command line arguments * @throws SAXException * @throws ParserConfigurationException * @throws XPathException * @throws IOException * @throws URISyntaxException */ public void go(String[] args) { if (args.Length == 0 || args[0] == "-?") { Console.WriteLine("SchemaTestSuiteDriver testDir [-w] [-onwards] -c:contributor? -s:setName? -g:groupName?"); } Processor processor = new Processor(true); Console.WriteLine("Testing Saxon " + processor.ProductVersion); testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } String testSetPattern = null; // TODO use a regex String testGroupPattern = null; String contributor = null; Hashtable exceptions = new Hashtable(); for (int i=1; i<args.Length; i++) { if (args[i] == ("-w")) { //showWarnings = true; } else if (args[i] == ("-onwards")) { onwards = true; } else if (args[i].StartsWith("-c:")) { contributor = args[i].Substring(3); } else if (args[i].StartsWith("-s:")) { testSetPattern = args[i].Substring(3); } else if (args[i].StartsWith("-g:")) { testGroupPattern = args[i].Substring(3); } else if (args[i] == "-?") { Console.WriteLine("Usage: SchemaTestSuiteDriver testDir [-w] [-s:testSetPattern] [-g:testGroupPattern]"); } } int total = 39700; int passed = 0; int failed = 0; try { xlinkHref = new QName("xlink", "http://www.w3.org/1999/xlink", "href"); QName testCaseNT = new QName("", "", "testcase"); QName commentNT = new QName("", "", "comment"); QName testSetRefNT = new QName(testNS, "testSetRef"); QName testGroupNT = new QName(testNS, "testGroup"); QName testSetNT = new QName(testNS, "testSet"); QName schemaTestNT = new QName(testNS, "schemaTest"); QName instanceTestNT = new QName(testNS, "instanceTest"); QName schemaDocumentNT = new QName(testNS, "schemaDocument"); QName instanceDocumentNT = new QName(testNS, "instanceDocument"); QName expectedNT = new QName(testNS, "expected"); QName currentNT = new QName(testNS, "current"); QName validityAtt = new QName("", "", "validity"); QName nameAtt = new QName("", "", "name"); QName contributorAtt = new QName("", "", "contributor"); QName setAtt = new QName("", "", "set"); QName groupAtt = new QName("", "", "group"); QName statusAtt = new QName("", "", "status"); QName bugzillaAtt = new QName("", "", "bugzilla"); QName targetNamespaceAtt = new QName("", "", "targetNamespace"); QName schemaVersion = new QName("saxon", "http://saxon.sf.net/", "schemaVersion"); DocumentBuilder builder = processor.NewDocumentBuilder(); builder.BaseUri = new Uri(testSuiteDir + "/"); XdmNode catalog = builder.Build( new FileStream(testSuiteDir + "/suite.xml", FileMode.Open, FileAccess.Read, FileShare.Read)); results = new StreamWriter(testSuiteDir + "/saxon/SaxonResults" + processor.ProductVersion + "n.xml"); results.Write("<testSuiteResults xmlns='" + testNS + "' xmlns:saxon='http://saxon.sf.net/' " + "suite='TS_2006' " + "processor='Saxon-SA (Java) 8.8++' submitDate='2007-01-05' publicationPermission='public'>\n"); XdmNode exceptionsDoc = builder.Build( new FileStream(testSuiteDir + "/saxon/exceptions.xml", FileMode.Open, FileAccess.Read, FileShare.Read)); IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "testcase")); while (exceptionTestCases.MoveNext()) { XdmNode testCase = (XdmNode)exceptionTestCases.Current; String set = testCase.GetAttributeValue(setAtt); String group = testCase.GetAttributeValue(groupAtt); String comment = getChildElement(testCase, commentNT).StringValue; exceptions[set + "#" + group] = comment; } IEnumerator testSets = catalog.EnumerateAxis(XdmAxis.Descendant, testSetRefNT); while (testSets.MoveNext()) { XdmNode testSetRef = (XdmNode)testSets.Current; XdmNode testSetDoc = getLinkedDocument(testSetRef, processor, false); XdmNode testSetElement = getChildElement(testSetDoc, testSetNT); if (testSetElement == null) { feedback.Message("test set doc has no TestSet child: " + testSetDoc.BaseUri, true); continue; } String testSetName = testSetElement.GetAttributeValue(nameAtt); if (testSetPattern != null && !testSetName.StartsWith(testSetPattern)) { continue; } if (contributor != null && contributor != testSetElement.GetAttributeValue(contributorAtt)) { continue; } bool needs11 = (testSetElement.GetAttributeValue(schemaVersion) == "1.1"); IEnumerator testGroups = testSetElement.EnumerateAxis(XdmAxis.Child, testGroupNT); while (testGroups.MoveNext()) { XdmNode testGroup = (XdmNode)testGroups.Current; String testGroupName = testGroup.GetAttributeValue(nameAtt); String exception = (String)exceptions[testSetName + "#" + testGroupName]; if (testGroupPattern != null && !testGroupName.StartsWith(testGroupPattern)) { continue; } Console.WriteLine("TEST SET " + testSetName + " GROUP " + testGroupName, false); if (onwards) { testGroupPattern = null; testSetPattern = null; } Processor testConfig = new Processor(true); if (needs11) { testConfig.SetProperty("http://saxon.sf.net/feature/xsd-version", "1.1"); } SchemaManager schemaManager = testConfig.SchemaManager; //testConfig.setHostLanguage(Configuration.XML_SCHEMA); testConfig.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true"); IEnumerator schemaTests = testGroup.EnumerateAxis(XdmAxis.Child, schemaTestNT); bool schemaQueried = false; String bugzillaRef = null; while (schemaTests.MoveNext()) { XdmNode schemaTest = (XdmNode)schemaTests.Current; if (schemaTest == null) { break; } bugzillaRef = null; String testName = schemaTest.GetAttributeValue(nameAtt); if (exception != null) { results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='notKnown' saxon:outcome='notRun' saxon:comment='" + exception + "'/>\n"); continue; } bool queried = false; XdmNode statusElement = getChildElement(schemaTest, currentNT); if (statusElement != null) { String status = statusElement.GetAttributeValue(statusAtt); queried = ("queried" == status); bugzillaRef = statusElement.GetAttributeValue(bugzillaAtt); } if (queried) { schemaQueried = true; } Console.WriteLine("TEST SCHEMA " + testName + (queried ? " (queried)" : "")); bool success = true; IEnumerator schemata = schemaTest.EnumerateAxis(XdmAxis.Child, schemaDocumentNT); while (schemata.MoveNext()) { XdmNode schemaDocumentRef = (XdmNode)schemata.Current; if (schemaDocumentRef == null) { break; } Console.WriteLine("Loading schema at " + schemaDocumentRef.GetAttributeValue(xlinkHref)); XdmNode schemaDoc = getLinkedDocument(schemaDocumentRef, testConfig, false); IEnumerator schemaDocKids = schemaDoc.EnumerateAxis(XdmAxis.Child); XdmNode schemaElement = null; while (schemaDocKids.MoveNext()) { schemaElement = (XdmNode)schemaDocKids.Current; if (schemaElement.NodeKind == XmlNodeType.Element) { break; } } String targetNamespace = schemaElement.GetAttributeValue(targetNamespaceAtt); //if (targetNamespace != null && schemaManager. isSchemaAvailable(targetNamespace)) { // do nothing // TODO: this is the only way I can get MS additional test addB132 to work. // It's not ideal: addSchemaSource() ought to be a no-op if the schema components // are already loaded, but in fact recompiling the imported schema document on its // own is losing the substitution group membership that was defined in the // importing document. //} else { IList errorList = new ArrayList(); schemaManager.ErrorList = errorList; try { schemaManager.Compile(schemaDoc); } catch (Exception e) { if (errorList.Count == 0) { feedback.Message("In " + testName + ", exception thrown but no errors in ErrorList\n", true); results.Write("<!--" + e.Message + "-->"); success = false; } } for (int i = 0; i < errorList.Count; i++) { if (errorList[i] is StaticError) { StaticError err = (StaticError)errorList[i]; if (!err.IsWarning) { success = false; break; } } else { feedback.Message("In " + testName + " wrong kind of error!" + errorList[i].GetType() + "\n", true); } } } XdmNode expected = getChildElement(schemaTest, expectedNT); bool expectedSuccess = expected==null || expected.GetAttributeValue(validityAtt) == "valid"; if (success == expectedSuccess) { passed++; } else { failed++; } feedback.Feedback(passed, failed, total); results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='" + (success ? "valid" : "invalid" ) + (queried ? "' saxon:queried='true' saxon:bugzilla='" + bugzillaRef : "") + "' saxon:outcome='" + (success==expectedSuccess ? "same" : "different") + "'/>\n"); } IEnumerator instanceTests = testGroup.EnumerateAxis(XdmAxis.Child, instanceTestNT); while (instanceTests.MoveNext()) { XdmNode instanceTest = (XdmNode)instanceTests.Current; String testName = instanceTest.GetAttributeValue(nameAtt); if (exception != null) { results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='notKnown' saxon:outcome='notRun' saxon:comment='" + exception + "'/>\n"); continue; } bool queried = false; XdmNode statusElement = getChildElement(instanceTest, currentNT); if (statusElement != null) { String status = statusElement.GetAttributeValue(statusAtt); queried = ("queried" == status); String instanceBug = statusElement.GetAttributeValue(bugzillaAtt); if (instanceBug != null) { bugzillaRef = instanceBug; } } queried |= schemaQueried; Console.WriteLine("TEST INSTANCE " + testName + (queried ? " (queried)" : "")); XdmNode instanceDocument = getChildElement(instanceTest, instanceDocumentNT); bool success = true; try { XdmNode instanceDoc = getLinkedDocument(instanceDocument, testConfig, true); } catch (Exception) { success = false; } XdmNode expected = getChildElement(instanceTest, expectedNT); bool expectedSuccess = expected==null || expected.GetAttributeValue(validityAtt) == "valid"; if (success == expectedSuccess) { passed++; } else { failed++; } feedback.Feedback(passed, failed, total); results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='" + (success ? "valid" : "invalid" ) + (queried ? "' saxon:queried='true' saxon:bugzilla='" + bugzillaRef : "") + "' saxon:outcome='" + (success==expectedSuccess ? "same" : "different") + "'/>\n"); } } } results.Write("</testSuiteResults>"); results.Close(); } catch (Exception e) { feedback.Message("Test failed: " + e.Message, true); } }
private XdmNode getChildElement(XdmNode parent, QName child) { IEnumerator e = parent.EnumerateAxis(XdmAxis.Child, child); return e.MoveNext() ? (XdmNode)e.Current : null; }
void Run(XmlDestination destination, XsltRuntimeOptions options) { if (options == null) throw new ArgumentNullException("options"); XsltTransformer transformer = executable.Load(); transformer.RecoveryPolicy = RecoveryPolicy.DoNotRecover; if (options.InputXmlResolver != null) transformer.InputXmlResolver = options.InputXmlResolver; // XsltTransformer.BaseOutputUri doesn't accept null if (options.BaseOutputUri != null) transformer.BaseOutputUri = options.BaseOutputUri; // TODO: Bug in Saxon 9.3 //else if (this.StaticBaseUri != null && this.StaticBaseUri.IsFile) // transformer.BaseOutputUri = new Uri(Path.GetDirectoryName(this.StaticBaseUri.LocalPath), UriKind.Absolute); try { if (options.InitialTemplate != null) transformer.InitialTemplate = new QName(options.InitialTemplate); } catch (DynamicError err) { throw new SaxonException(err); } if (options.InitialMode != null) transformer.InitialMode = new QName(options.InitialMode); if (options.InitialContextNode != null) transformer.InitialContextNode = options.InitialContextNode.ToXdmNode(this.Processor.ItemFactory); transformer.MessageListener = new SaxonMessageListener(); foreach (var pair in options.Parameters) { QName qname = new QName(pair.Key); XdmValue xdmValue = pair.Value.ToXdmValue(this.Processor.ItemFactory); transformer.SetParameter(qname, xdmValue); } try { transformer.Run(destination); } catch (DynamicError ex) { throw new SaxonException(ex); } catch (Exception ex) { throw new SaxonException(ex.Message, ex); } }
public void go(String[] args) { int passed = 0; int failed = 0; int total = 0; testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } Hashtable exceptions = new Hashtable(); if (args.Length > 1) { testPattern = (args[1]); } for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-w")) { //showWarnings = true; } } try { schemaAwareProcessor = new Processor(true); } catch (Exception) { Console.WriteLine("Cannot load Saxon-SA: continuing without it"); } processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true"); if (schemaAwareProcessor != null) { schemaAwareProcessor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true"); } fileComparer = new FileComparer(processor, testSuiteDir); String testURI = "http://www.w3.org/2005/05/xslt20-test-catalog"; QName testCaseNT = new QName(testURI, "testcase"); QName nameNT = new QName(testURI, "name"); QName inputNT = new QName(testURI, "input"); QName outputNT = new QName(testURI, "output"); QName stylesheetNT = new QName(testURI, "stylesheet"); QName schemaNT = new QName(testURI, "schema"); QName initialModeNT = new QName(testURI, "initial-mode"); QName entryNamedTemplateNT = new QName(testURI, "entry-named-template"); QName sourceDocumentNT = new QName(testURI, "source-document"); QName stylesheetParametersNT = new QName(testURI, "stylesheet-parameters"); QName paramNT = new QName(testURI, "param"); QName resultDocumentNT = new QName(testURI, "result-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 discretionaryVersionNT = new QName(testURI, "discretionary-version"); QName initialContextNodeNT = new QName(testURI, "initial-context-node"); QName fileAtt = new QName("", "file"); QName errorIdAtt = new QName("", "error-id"); QName typeAtt = new QName("", "type"); QName nameAtt = new QName("", "name"); QName behaviorAtt = new QName("", "behavior"); QName specAtt = new QName("", "spec"); QName qnameAtt = new QName("", "qname"); QName modeAtt = new QName("", "mode"); QName validatesAtt = new QName("", "validates"); QName roleAtt = new QName("", "role"); DocumentBuilder builder = processor.NewDocumentBuilder(); XdmNode exceptionsDoc = builder.Build(new Uri(testSuiteDir + '/' + getResultDirectoryName() + "/exceptions.xml")); IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (exceptionTestCases.MoveNext()) { XdmNode n = (XdmNode)exceptionTestCases.Current; String nameAttVal = n.GetAttributeValue(nameAtt); char[] seps = { ' ', '\n', '\t' }; String[] parts = nameAttVal.Split(seps); foreach (string p in parts) { if (!exceptions.ContainsKey(p)) { exceptions.Add(p, "Kilroy"); } } } XdmNode catalog = builder.Build(new Uri(testSuiteDir + "/catalog.xml")); results = new StreamWriter(testSuiteDir + "/SaxonResults.net/results" + processor.ProductVersion + ".xml"); log = new StreamWriter(testSuiteDir + "/SaxonResults.net/log" + processor.ProductVersion + "n.xml"); log.WriteLine("Testing Saxon " + processor.ProductVersion); results.WriteLine("<test-suite-result>"); results.WriteLine(" <implementation name='Saxon-SA' version='" + processor.ProductVersion + "' anonymous-result-column='false'>"); results.WriteLine(" <organization name='http://www.saxonica.com/' anonymous='false'/>"); results.WriteLine(" <submitter name='Michael Kay' email='*****@*****.**'/>"); outputDiscretionaryItems(); results.WriteLine(" </implementation>"); total = 0; IEnumerator testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { total++; } testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { bool useAssociated = false; XdmNode testCase = (XdmNode)testCases.Current; String testName = getChildElement(testCase, nameNT).StringValue; if (testPattern != null && !testName.StartsWith(testPattern)) { continue; } if (exceptions.ContainsKey(testName)) { continue; } if (isExcluded(testName)) { continue; } log.WriteLine("Test " + testName); XdmNode testInput = getChildElement(testCase, inputNT); XdmNode stylesheet = getChildElement(testInput, stylesheetNT); String absXSLName = null; if (stylesheet == null) { useAssociated = true; } else { absXSLName = testSuiteDir + "/TestInputs/" + stylesheet.GetAttributeValue(fileAtt); } XdmNode sourceDocument = getChildElement(testInput, sourceDocumentNT); String absXMLName = null; if (sourceDocument != null) { absXMLName = testSuiteDir + "/TestInputs/" + sourceDocument.GetAttributeValue(fileAtt); } bool schemaAware = false; bool recoverRecoverable = true; bool backwardsCompatibility = true; bool supportsDOE = true; bool recoverSESU0007 = false; bool useXSLT30 = false; XdmNode discretionaryItems = getChildElement(testCase, discretionaryItemsNT); if (discretionaryItems != null) { IEnumerator features = discretionaryItems.EnumerateAxis(XdmAxis.Child, discretionaryFeatureNT); while (features.MoveNext()) { XdmNode feature = (XdmNode)features.Current; String featureName = feature.GetAttributeValue(nameAtt); if ("schema_aware".Equals(featureName) || "Saxon-PE".Equals(featureName)) // TODO: test Saxon-PE properly { schemaAware = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } else if ("XML_1.1".Equals(featureName)) { xml11 = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } else if ("backwards_compatibility".Equals(featureName)) { backwardsCompatibility = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } else if ("disabling_output_escaping".Equals(featureName)) { supportsDOE = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } } IEnumerator choices = discretionaryItems.EnumerateAxis( XdmAxis.Child, discretionaryChoiceNT); while (choices.MoveNext()) { XdmNode choice = (XdmNode)choices.Current; String featureName = choice.GetAttributeValue(nameAtt); if ("error".Equals(choice.GetAttributeValue(behaviorAtt))) { recoverRecoverable = false; } else if ("SESU0007".Equals(featureName)) { recoverSESU0007 = "recovery".Equals(choice.GetAttributeValue(behaviorAtt)); } } IEnumerator versions = discretionaryItems.EnumerateAxis( XdmAxis.Child, discretionaryVersionNT); while (versions.MoveNext()) { XdmNode dv = (XdmNode)versions.Current; useXSLT30 = ("XSLT30" == dv.GetAttributeValue(specAtt)); } } if (!backwardsCompatibility) { // Saxon cannot run with BC switched off results.WriteLine(" <testcase name='" + testName + "' result='not run' comment='requires backwards-compatibility=off'/>"); continue; } if (!supportsDOE) { // Saxon cannot run with DOE switched off results.WriteLine(" <testcase name='" + testName + "' result='not run' comment='requires disable-output-escaping=off'/>"); continue; } if (recoverSESU0007) { // Saxon cannot recover from error SESU0007 results.WriteLine(" <testcase name='" + testName + "' result='not run' comment='requires recovery from error SESU0007'/>"); continue; } XdmNode initialMode = getChildElement(testInput, initialModeNT); QName initialModeName = null; if (initialMode != null) { String ini = initialMode.GetAttributeValue(qnameAtt); initialModeName = makeQName(ini, initialMode); } XdmNode initialTemplate = getChildElement(testInput, entryNamedTemplateNT); QName initialTemplateName = null; if (initialTemplate != null) { String ini = initialTemplate.GetAttributeValue(qnameAtt); initialTemplateName = makeQName(ini, initialTemplate); } XdmNode initialContextNode = getChildElement(testInput, initialContextNodeNT); String initialContextPath = null; if (initialContextNode != null) { initialContextPath = initialContextNode.StringValue; } XdmNode validation = getChildElement(testInput, validationNT); String validationMode = null; if (validation != null) { validationMode = validation.GetAttributeValue(modeAtt); } Hashtable paramTable = null; XdmNode paramList = getChildElement(testInput, stylesheetParametersNT); if (paramList != null) { paramTable = new Hashtable(5); IEnumerator paramIter = paramList.EnumerateAxis(XdmAxis.Child, paramNT); while (paramIter.MoveNext()) { XdmNode param = (XdmNode)paramIter.Current; QName name = makeQName(param.GetAttributeValue(qnameAtt), param); String value = param.StringValue; paramTable.Add(name, value); } } IEnumerator schemas = testInput.EnumerateAxis(XdmAxis.Child, schemaNT); while (schemas.MoveNext()) { XdmNode schema = (XdmNode)schemas.Current; if (schema == null) { break; } schemaAware = true; String role = schema.GetAttributeValue(roleAtt); if (("source-validator".Equals(role) || "source-reference".Equals(role)) /* && schema.GetAttributeValue(validatesAtt) != null */) { validationMode = "strict"; // TODO: control which source documents are validated... } } XdmNode testOutput = getChildElement(testCase, outputNT); XdmNode resultDocument = getChildElement(testOutput, resultDocumentNT); // TODO: handle alternative result documents String refFileName = null; String outFileName; String comparator = "xml"; if (resultDocument != null) { String relativePath = resultDocument.GetAttributeValue(fileAtt); int slash = relativePath.IndexOf('/'); if (slash > 0) { String relativeDir = relativePath.Substring(0, slash); String fullDir = testSuiteDir + '/' + getResultDirectoryName() + "/" + relativeDir; if (!Directory.Exists(fullDir)) { Directory.CreateDirectory(fullDir); } } refFileName = testSuiteDir + "/ExpectedTestResults/" + relativePath; outFileName = testSuiteDir + '/' + getResultDirectoryName() + "/" + relativePath; comparator = resultDocument.GetAttributeValue(typeAtt); } else { outFileName = testSuiteDir + '/' + getResultDirectoryName() + "/temp.out"; } XdmNode error = getChildElement(testOutput, errorNT); String expectedError = null; if (error != null) { expectedError = error.GetAttributeValue(errorIdAtt); } bool success; Exception xsltOutcome = runXSLT(testName, absXMLName, absXSLName, initialModeName, initialTemplateName, outFileName, paramTable, initialContextPath, useAssociated, schemaAware, validationMode, recoverRecoverable, useXSLT30); if (xsltOutcome == null) { success = true; if (expectedError != null && resultDocument == null) { log.WriteLine("Test failed. Expected error " + expectedError + ", got success"); feedback.Feedback(passed, failed++, total); success = false; results.WriteLine(" <testcase name='" + testName + "' result='differ' comment='Expected error " + expectedError + ", got success'/>"); } else { feedback.Feedback(passed++, failed, total); } } else { String errorCode = null; if (xsltOutcome is StaticError) { errorCode = ((StaticError)xsltOutcome).ErrorCode.LocalName; } else if (xsltOutcome is DynamicError) { errorCode = ((DynamicError)xsltOutcome).ErrorCode.LocalName; } if (expectedError != null && errorCode != null && errorCode.Equals(expectedError)) { feedback.Feedback(passed++, failed, total); log.WriteLine("Test succeeded (" + expectedError + ')'); results.WriteLine(" <testcase name='" + testName + "' result='full' comment='Error " + expectedError + " as expected'/>"); } else if (expectedError != null) { feedback.Feedback(passed++, failed, total); log.WriteLine("Test succeeded (??) (expected " + expectedError + ", got " + errorCode + ')'); results.WriteLine(" <testcase name='" + testName + "' result='different-error' comment='Expected " + expectedError + " got " + errorCode + "'/>"); } else { feedback.Feedback(passed, failed++, total); log.WriteLine("Test failed. Expected success, got " + errorCode); results.WriteLine(" <testcase name='" + testName + "' result='differ' comment='Expected success, got " + errorCode + "'/>"); results.WriteLine(" <!--" + xsltOutcome.Message + "-->"); } success = false; continue; } if (success) { String outcome = fileComparer.compare(outFileName, refFileName, comparator); if (outcome == "OK") { results.WriteLine(" <testcase name='" + testName + "' result='full'/>"); } else if (outcome.StartsWith("#")) { results.WriteLine(" <testcase name='" + testName + "' result='full' + comments='" + outcome.Substring(1) + "/>"); } else { results.WriteLine(" <testcase name='" + testName + "' result='differ' comments='" + outcome + "'/>"); } } } results.WriteLine("</test-suite-result>"); results.Close(); log.Close(); //} }
/// <summary> /// Declare a variable for use by the XPath expression. If the expression /// refers to any variables, then they must be declared here. /// </summary> /// <param name="name">The name of the variable, as a <c>QName</c></param> public void DeclareVariable(QName name) { env.declareVariable(name.ToQNameValue()); }
public void processCatalog(string catalogFile) { DocumentBuilder builder = driverProc.NewDocumentBuilder(); XdmNode catalog = builder.Build(new Uri(catalogFile)); DocumentBuilder catbuilder = driverProc.NewDocumentBuilder(); //catbuilder.SetTreeModel(treeModel); XPathCompiler xpc = driverProc.NewXPathCompiler(); xpc.BaseUri = "";// catalogFile; xpc.XPathLanguageVersion = "3.0"; xpc.Caching = true; xpc.DeclareNamespace("", "http://www.w3.org/2010/09/qt-fots-catalog"); IEnumerator en = xpc.Evaluate("//environment", catalog).GetEnumerator(); while (en.MoveNext()) { XdmNode envi = (XdmNode)en.Current; processEnvironment(xpc, envi, globalEnvironments); } try { WriteResultFilePreamble(driverProc, catalog, DateTime.Today.ToString()); } catch (Exception e) { feedback.Message(e.StackTrace, false); } /** * Look for an exceptions.xml document with the general format: * * <exceptions xmlns="...test catalog namespace..."> * <exception test-set ="testset1" test-case="testcase" run="yes/no/not-unfolded" * bug="bug-reference" reason=""> * <results> * ... alternative expected results ... * </results> * <optimization> * ... assertions about the "explain" tree * </optimization> * </exception> * </exceptions> * */ XdmNode exceptionsDoc = null; DocumentBuilder exceptBuilder = driverProc.NewDocumentBuilder(); QName testCase = new QName("", "test-case"); try { exceptionsDoc = exceptBuilder.Build(new Uri(resultsDir + "/exceptions.xml")); //XdmSequenceIterator iter IEnumerator iter = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName(RNS, "exception")); while (iter.MoveNext()) { XdmNode entry = (XdmNode)iter.Current; string test = entry.GetAttributeValue(testCase); if (test != null) { exceptionsMap.Add(test, entry); } } } catch (Exception e) { Console.WriteLine("*** Failed to process exceptions file: " + e.Message); } if (testFuncSet != null) { try { XdmNode funcSetNode = (XdmNode)xpc.EvaluateSingle("//test-set[@name='" + testFuncSet + "']", catalog); if (funcSetNode == null) { throw new Exception("Test-set " + testFuncSet + " not found!"); } processTestSet(catbuilder, xpc, funcSetNode); } catch (Exception e1) { // e1.printStackTrace(); } } else { en = xpc.Evaluate("//test-set", catalog).GetEnumerator(); while (en.MoveNext()) { processTestSet(catbuilder, xpc, ((XdmNode)en.Current)); } } try { writeResultFilePostamble(); } catch (Exception e) { // e.printStackTrace(); } }
/// <summary>Locate and compile a stylesheet identified by an <?xml-stylesheet?> /// processing instruction within a source document. /// </summary> /// <param name="source">The document node of the source document containing the /// xml-stylesheet processing instruction.</param> /// <returns>An <c>XsltExecutable</c> which represents the compiled stylesheet object.</returns> /// <remarks>There are some limitations in the current implementation. The media type /// is ignored, as are the other parameters of the xml-stylesheet instruction. The /// href attribute must either reference an embedded stylesheet within the same /// document or a non-embedded external stylesheet.</remarks> public XsltExecutable CompileAssociatedStylesheet(XdmNode source) { // TODO: lift the restrictions if (source == null || source.NodeKind != XmlNodeType.Document) { throw new ArgumentException("Source must be a document node"); } IEnumerator kids = source.EnumerateAxis(XdmAxis.Child); QName xmlstyle = new QName("", "xml-stylesheet"); while (kids.MoveNext()) { XdmNode n = (XdmNode)kids.Current; if (n.NodeKind == XmlNodeType.ProcessingInstruction && n.NodeName.Equals(xmlstyle)) { // TODO: check the media type String href = JProcInstParser.getPseudoAttribute(n.StringValue, "href"); if (href == null) { throw new DynamicError("xml-stylesheet processing instruction has no href attribute"); } String fragment = null; int hash = href.LastIndexOf('#'); if (hash == 0) { if (href.Length == 1) { throw new DynamicError("Relative URI of '#' is invalid"); } fragment = href.Substring(1); JNodeInfo target = ((JDocumentInfo)source.value).selectID(fragment); XdmNode targetWrapper = null; if (target == null) { // There's a problem here because the Microsoft XML parser doesn't // report id values, so selectID() will never work. We work around that // by looking for an attribute named "id" appearing on an xsl:stylesheet // or xsl:transform element QName qid = new QName("", "id"); IEnumerator en = source.EnumerateAxis(XdmAxis.Descendant); while (en.MoveNext()) { XdmNode x = (XdmNode)en.Current; if (x.NodeKind == XmlNodeType.Element && x.NodeName.Uri == "http://www.w3.org/1999/XSL/Transform" && (x.NodeName.LocalName == "stylesheet" || x.NodeName.LocalName == "transform" && x.GetAttributeValue(qid) == fragment)) { targetWrapper = x; } } } else { targetWrapper = (XdmNode)XdmValue.Wrap(target); } if (targetWrapper == null) { throw new DynamicError("No element with id='" + fragment + "' found"); } return(Compile(targetWrapper)); } else if (hash > 0) { throw new NotImplementedException("href cannot identify an embedded stylesheet in a different document"); } else { Uri uri = new Uri(n.BaseUri, href); return(Compile(uri)); } } } throw new DynamicError("xml-stylesheet processing instruction not found"); }
/// <summary> /// Get the value that has set for a schema processor (a parameter defined in the schema using the <c>saxon:param</c> /// extension) /// </summary> /// <param name="name">the parameter whose name is required</param> /// <returns>the value that has been set for the parameter, or the EmptySequence if no value has been set</returns> public XdmValue GetParameter(QName name) { net.sf.saxon.s9api.XdmValue value = schemaValidator.getParameter(name.UnderlyingQName()); return(value == null ? null : XdmValue.Wrap(value.getUnderlyingValue())); }
/// <summary> /// Set the value of a variable /// </summary> /// <param name="name">The name of the variable. This must match the name of a variable /// that was declared to the XPathCompiler. No error occurs if the expression does not /// actually reference a variable with this name.</param> /// <param name="value">The value to be given to the variable.</param> public void SetVariable(QName name, XdmValue value) { JXPathVariable var = null; String uri = (name.Uri == null ? "" : name.Uri); String local = name.LocalName; foreach (JXPathVariable v in declaredVariables) { String vuri = v.getVariableQName().getURI(); if (vuri == null) { vuri = ""; } if (vuri == uri && v.getVariableQName().getLocalPart() == local) { var = v; break; } } if (var == null) { // TODO: this seems to conflict with the documentation of the method throw new ArgumentException("Variable has not been declared: " + name); } dynamicContext.setVariable(var, value.Unwrap()); }
/// <summary> /// Set the value of a stylesheet parameter. /// </summary> /// <param name="name">The name of the parameter, expressed /// as a QName. If a parameter of this name has been declared in the /// stylesheet, the given value will be assigned to the variable. If the /// variable has not been declared, calling this method has no effect (it is /// not an error).</param> /// <param name="value">The value to be given to the parameter. /// If the parameter declaration defines a required type for the variable, then /// this value will be converted in the same way as arguments to function calls /// (for example, numeric promotion is applied).</param> public void SetParameter(QName name, XdmValue value) { controller.setParameter(name.ClarkName, value.Unwrap()); }
/// <summary> /// Set the value of an external variable declared in the query. /// </summary> /// <param name="name">The name of the external variable, expressed /// as a QName. If an external variable of this name has been declared in the /// query prolog, the given value will be assigned to the variable. If the /// variable has not been declared, calling this method has no effect (it is /// not an error).</param> /// <param name="value">The value to be given to the external variable. /// If the variable declaration defines a required type for the variable, then /// this value must match the required type: no conversions are applied.</param> public void SetExternalVariable(QName name, XdmValue value) { context.setParameter(name.ClarkName, value.Unwrap()); }
/** * Run the application */ public void go(String filename) { Processor processor = new Processor(); XPathCompiler xpe = processor.NewXPathCompiler(); // Build the source document. DocumentBuilder builder = processor.NewDocumentBuilder(); builder.BaseUri = new Uri(filename); builder.WhitespacePolicy = WhitespacePolicy.StripAll; XdmNode indoc = builder.Build( new FileStream(filename, FileMode.Open, FileAccess.Read)); // Compile the XPath expressions used by the application QName wordName = new QName("", "", "word"); xpe.DeclareVariable(wordName); XPathSelector findLine = xpe.Compile("//LINE[contains(., $word)]").Load(); XPathSelector findLocation = xpe.Compile("concat(ancestor::ACT/TITLE, ' ', ancestor::SCENE/TITLE)").Load(); XPathSelector findSpeaker = xpe.Compile("string(ancestor::SPEECH/SPEAKER[1])").Load(); // Loop until the user enters "." to end the application while (true) { // Prompt for input Console.WriteLine("\n>>>> Enter a word to search for, or '.' to quit:\n"); // Read the input String word = Console.ReadLine().Trim(); if (word == ".") { break; } if (word != "") { // Set the value of the XPath variable currentWord = word; // Find the lines containing the requested word bool found = false; findLine.ContextItem = indoc; findLine.SetVariable(wordName, new XdmAtomicValue(word)); foreach (XdmNode line in findLine) { // Note that we have found at least one line found = true; // Find where it appears in the play findLocation.ContextItem = line; Console.WriteLine("\n" + findLocation.EvaluateSingle()); // Output the name of the speaker and the content of the line findSpeaker.ContextItem = line; Console.WriteLine(findSpeaker.EvaluateSingle() + ": " + line.StringValue); } // If no lines were found, say so if (!found) { Console.WriteLine("No lines were found containing the word '" + word + '\''); } } } // Finish when the user enters "." Console.WriteLine("Finished."); }
/// <summary> /// Declare a variable for use by the XPath expression. If the expression /// refers to any variables, then they must be declared here, unless the /// <c>AllowUndeclaredVariables</c> property has been set to true. /// </summary> /// <param name="name">The name of the variable, as a <c>QName</c></param> public void DeclareVariable(QName name) { JXPathVariable var = env.declareVariable(name.ToQNameValue()); //declaredVariables.Add(var); }
/// <summary> /// Construct an atomic value of type <c>xs:QName</c> /// </summary> /// <param name="q">The QName value</param> public XdmAtomicValue(QName q) { this.value = new QNameValue( q.Prefix, q.Uri, q.LocalName, null); }
XQueryEvaluator GetEvaluator(XQueryRuntimeOptions options) { if (options == null) throw new ArgumentNullException("options"); XQueryEvaluator eval = this.executable.Load(); if (options.InputXmlResolver != null) eval.InputXmlResolver = options.InputXmlResolver; if (options.ContextItem != null) eval.ContextItem = options.ContextItem.ToXdmItem(this.Processor.ItemFactory); foreach (var pair in options.ExternalVariables) { QName qname = new QName(pair.Key); XdmValue xdmValue = pair.Value.ToXdmValue(this.Processor.ItemFactory); eval.SetExternalVariable(qname, xdmValue); } return eval; }
public HttpMethod() { this._FunctionName = new QName(RequestModule.Namespace, "http-method"); this._ArgumentTypes = new XdmSequenceType[0]; this.resultType = new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '); }
/// <summary>Locate and compile a stylesheet identified by an <?xml-stylesheet?> /// processing instruction within a source document. /// </summary> /// <param name="source">The document node of the source document containing the /// xml-stylesheet processing instruction.</param> /// <returns>An <c>XsltExecutable</c> which represents the compiled stylesheet object.</returns> /// <remarks>There are some limitations in the current implementation. The media type /// is ignored, as are the other parameters of the xml-stylesheet instruction. The /// href attribute must either reference an embedded stylesheet within the same /// document or a non-embedded external stylesheet.</remarks> public XsltExecutable CompileAssociatedStylesheet(XdmNode source) { // TODO: lift the restrictions if (source == null || source.NodeKind != XmlNodeType.Document) { throw new ArgumentException("Source must be a document node"); } IEnumerator kids = source.EnumerateAxis(XdmAxis.Child); QName xmlstyle = new QName("", "xml-stylesheet"); while (kids.MoveNext()) { XdmNode n = (XdmNode)kids.Current; if (n.NodeKind == XmlNodeType.ProcessingInstruction && n.NodeName.Equals(xmlstyle)) { // TODO: check the media type String href = JProcInstParser.getPseudoAttribute(n.StringValue, "href"); if (href == null) { throw new DynamicError("xml-stylesheet processing instruction has no href attribute"); } String fragment = null; int hash = href.LastIndexOf('#'); if (hash == 0) { if (href.Length == 1) { throw new DynamicError("Relative URI of '#' is invalid"); } fragment = href.Substring(1); JNodeInfo target = ((JDocumentInfo)source.value).selectID(fragment, true); XdmNode targetWrapper = null; if (target == null) { // There's a problem here because the Microsoft XML parser doesn't // report id values, so selectID() will never work. We work around that // by looking for an attribute named "id" appearing on an xsl:stylesheet // or xsl:transform element QName qid = new QName("", "id"); IEnumerator en = source.EnumerateAxis(XdmAxis.Descendant); while (en.MoveNext()) { XdmNode x = (XdmNode)en.Current; if (x.NodeKind == XmlNodeType.Element && x.NodeName.Uri == "http://www.w3.org/1999/XSL/Transform" && (x.NodeName.LocalName == "stylesheet" || x.NodeName.LocalName == "transform" && x.GetAttributeValue(qid) == fragment)) { targetWrapper = x; } } } else { targetWrapper = (XdmNode)XdmValue.Wrap(target); } if (targetWrapper == null) { throw new DynamicError("No element with id='" + fragment + "' found"); } return Compile(targetWrapper); } else if (hash > 0) { throw new NotImplementedException("href cannot identify an embedded stylesheet in a different document"); } else { Uri uri = new Uri(n.BaseUri, href); return Compile(uri); } } } throw new DynamicError("xml-stylesheet processing instruction not found"); }
/// <summary> /// Run the transformation /// </summary> /// <param name="testName"></param> /// <param name="xml"></param> /// <param name="xsl"></param> /// <param name="initialMode"></param> /// <param name="initialTemplate"></param> /// <param name="outfile"></param> /// <param name="paramTable"></param> /// <param name="initialContextPath"></param> /// <param name="useAssociated"></param> /// <param name="schemaAware"></param> /// <param name="validationMode"></param> /// <param name="recoverRecoverable"></param> /// <returns>Either null, indicating success, or an Exception object with information about the failure</returns> protected Exception 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, bool useXSLT30) { Serializer sr = new Serializer(); sr.SetOutputFile(outfile); Processor f; if (noCacheTests.ContainsKey(testName)) { //create a custom Processor to avoid schema caching f = new Processor(true); } else if (schemaAware) { f = schemaAwareProcessor; if (f == null) { return new DynamicError("Saxon-SA not available"); } } 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.SchemaAware = schemaAware; compiler.ErrorList = errors; if (useXSLT30) { compiler.XsltLanguageVersion = "3.0"; } XsltExecutable sheet = null; XsltTransformer inst; if (useAssociated) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { log.WriteLine("Failed to build source document: " + e.Message); return e; } try { sheet = compiler.CompileAssociatedStylesheet(source); } catch (Exception e) { log.WriteLine("Failed to compile stylesheet: " + e.Message); if (errors.Count > 0) { return (Exception)errors[0]; //QName code = ((StaticError)errors[0]).ErrorCode; //(code == null ? "Failed to compile stylesheet: " + e.Message : code.LocalName); } else { return e; } } } else { Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read); compiler.BaseUri = new Uri(xsl); try { sheet = compiler.Compile(stream); } catch (StaticError e) { if (errors.Count > 0) { return ((StaticError)errors[0]); } else { log.WriteLine(e.Message); return e; } } catch (Exception e2) { log.WriteLine("Unexpected CRASH: " + e2.Message); log.WriteLine(e2.StackTrace); return e2; } finally { stream.Close(); } } if (initialContextPath != null) { if (source == null && xml != null) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { log.WriteLine("Failed to build source document: " + e.Message); return e; } } 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 (source != null) { inst.InitialContextNode = source; } if (source == null && xml != null) { Stream stream = new FileStream(xml, FileMode.Open, FileAccess.Read); inst.SetInputStream(stream, new Uri(xml)); } if (initialMode != null) { inst.InitialMode = initialMode; } if (initialTemplate != null) { try { inst.InitialTemplate = initialTemplate; } catch (DynamicError e) { return e; } } if (paramTable != null) { foreach (DictionaryEntry de in paramTable) { inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString())); } } inst.BaseOutputUri = new Uri(outfile); inst.RecoveryPolicy = recoverRecoverable ? RecoveryPolicy.RecoverSilently : RecoveryPolicy.DoNotRecover; if ("strict" == validationMode) { inst.SchemaValidationMode = SchemaValidationMode.Strict; } else { inst.SchemaValidationMode = SchemaValidationMode.None; } //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) { log.WriteLine(e.Message); return e; } catch (Exception e2) { log.WriteLine("Unexpected CRASH: " + e2.Message); log.WriteLine(e2.StackTrace); return e2; } return null; // indicating success }
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>Set a serialization property</summary> /// <remarks>In the case of XSLT, properties set within the serializer override /// any properties set in <c>xsl:output</c> declarations in the stylesheet. /// Similarly, with XQuery, they override any properties set in the Query /// prolog using <c>declare option saxon:output</c>.</remarks> /// <example> /// <code> /// Serializer qout = new Serializer(); /// qout.SetOutputProperty(Serializer.METHOD, "xml"); /// qout.SetOutputProperty(Serializer.INDENT, "yes"); /// qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1"); /// </code> /// </example> /// <param name="name">The name of the serialization property to be set</param> /// <param name="value">The value to be set for the serialization property. May be null /// to unset the property (that is, to set it back to the default value).</param> public void SetOutputProperty(QName name, String value) { props.setProperty(name.ClarkName, value); }
/// <summary> /// Declare a variable for use by the XPath expression. If the expression /// refers to any variables, then they must be declared here, unless the /// <c>AllowUndeclaredVariables</c> property has been set to true. /// </summary> /// <param name="name">The name of the variable, as a <c>QName</c></param> public void DeclareVariable(QName name) { compiler.declareVariable(name.UnderlyingQName()); }
public UrlAppRelativeFilePath() { this._FunctionName = new QName(RequestModule.Namespace, "url-app-relative-file-path"); this._ArgumentTypes = new XdmSequenceType[0]; this.resultType = new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_STRING), ' '); }
/// <summary> /// Get an <c>XdmAtomicType</c> object representing a built-in atomic type with a given name. /// </summary> /// <param name="name">The name of the required built-in atomic type</param> /// <returns>An <c>XdmAtomicType</c> object representing the built-in atomic type with the supplied name. /// Returns null if there is no built-in atomic type with this name. /// It is undefined whether two requests for the same built-in type will return the same object.</returns> public static XdmAtomicType BuiltInAtomicType(QName name) { int fingerprint = JStandardNames.getFingerprint(name.Uri, name.LocalName); return(BuiltInAtomicType(fingerprint)); }
/** * 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> /// Sets a property of a selected decimal format, for use by the <c>format-number</c> function. /// </summary> /// <remarks> /// This method checks that the value is valid for the particular property, but it does not /// check that all the values for the decimal format are consistent (for example, that the /// decimal separator and grouping separator have different values). This consistency /// check is performed only when the decimal format is used. /// </remarks> /// <param name="format">The name of the decimal format whose property is to be set. /// Supply null to set a property of the default (unnamed) decimal format. /// This correponds to a name used in the third argument of <c>format-number</c>.</param> /// <param name="property">The name of the property to set: one of /// "decimal-separator", "grouping-separator", "infinity", "NaN", /// "minus-sign", "percent", "per-mille", "zero-digit", "digit", /// or "pattern-separator".</param> /// <param name="value">The new value for the property.</param> public void SetDecimalFormatProperty(QName format, String property, String value) { net.sf.saxon.trans.DecimalFormatManager dfm = env.getDecimalFormatManager(); if (dfm == null) { dfm = new net.sf.saxon.trans.DecimalFormatManager(); env.setDecimalFormatManager(dfm); } net.sf.saxon.om.StructuredQName sqname = null; net.sf.saxon.trans.DecimalSymbols symbols = null; if (format != null) { sqname = net.sf.saxon.om.StructuredQName.fromClarkName(format.ClarkName); symbols = dfm.obtainNamedDecimalFormat(sqname); } else { symbols = dfm.getDefaultDecimalFormat(); } if (property.Equals("decimal-separator")) { symbols.setDecimalSeparator(value); } else if (property.Equals("grouping-separator")) { symbols.setGroupingSeparator(value); } else if (property.Equals("infinity")) { symbols.setInfinity(value); } else if (property.Equals("NaN")) { symbols.setNaN(value); } else if (property.Equals("minus-sign")) { symbols.setMinusSign(value); } else if (property.Equals("percent")) { symbols.setPercent(value); } else if (property.Equals("per-mille")) { symbols.setPerMille(value); } else if (property.Equals("zero-digit")) { symbols.setZeroDigit(value); if (!net.sf.saxon.trans.DecimalSymbols.isValidZeroDigit(symbols.getZeroDigit())) { throw new ArgumentException("Value supplied for zero-digit is not a Unicode digit representing zero"); } } else if (property.Equals("digit")) { symbols.setDigit(value); } else if (property.Equals("pattern-separator")) { symbols.setPatternSeparator(value); } else { throw new ArgumentException("Unknown decimal format property " + property); } }