private void writeModuleReportXQuery(string paperName, string className, StreamWriter sw) { Processor pr = new Processor(); XQueryCompiler xqc = pr.NewXQueryCompiler(); string errPath = "Papers\\" + paperName + "\\" + className + "_err.xml"; XmlDocument errdoc = new XmlDocument(); errdoc.Load(errPath); XmlElement root = errdoc.DocumentElement; XmlNodeList ruleNodes = root.GetElementsByTagName("err-rule"); foreach (XmlNode xrule in ruleNodes) { string rule = xrule.InnerText; //Console.WriteLine(rule); XQueryExecutable xqe = xqc.Compile(rule); XQueryEvaluator xqev = xqe.Load(); XdmValue result = xqev.Evaluate(); //对比结果 foreach (XdmItem rs in result) { sw.WriteLine(count + ". " + rs.ToString().Trim()); count++; } } }
/** * Show a query producing a sequence as its result and returning the sequence * to the Java application in the form of an iterator. For each item in the * result, its string value is output. */ public static void ExampleToSequence() { Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); XQueryExecutable exp = compiler.Compile("for $i in 1 to 10 return $i * $i"); XQueryEvaluator eval = exp.Load(); XdmValue value = eval.Evaluate(); IEnumerator e = value.GetEnumerator(); while (e.MoveNext()) { XdmItem item = (XdmItem)e.Current; Console.WriteLine(item.ToString()); } }
public override IEnumerable <XPathItem> Run(XQueryRuntimeOptions options) { XQueryEvaluator eval = GetEvaluator(options); XdmValue val; try { val = eval.Evaluate(); } catch (DynamicError ex) { throw new SaxonException(ex); } catch (Exception ex) { throw new SaxonException(ex.Message, ex); } return(val.ToXPathItems()); }
public List <MetadataAttributes> GetGeo(string granularity, bool distinct = true) { string query = ""; if (granularity.Equals("Country", StringComparison.InvariantCultureIgnoreCase)) { query = String.Format(distinct ? XQueries.ExtractGeoArray : XQueries.ExtractGeoArray2, "Country"); } else if (granularity.Equals("Region", StringComparison.InvariantCultureIgnoreCase)) { query = String.Format(distinct ? XQueries.ExtractGeoArray : XQueries.ExtractGeoArray2, "Region"); } else if (granularity.Equals("City", StringComparison.InvariantCultureIgnoreCase)) { query = String.Format(distinct ? XQueries.ExtractGeoArray : XQueries.ExtractGeoArray2, "City"); } else { query = String.Format(distinct ? XQueries.ExtractGeoArray : XQueries.ExtractGeoArray2, "Street"); }; List <MetadataAttributes> ts = new List <MetadataAttributes>(); Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = BaseUri; XQueryExecutable exp = compiler.Compile(query); XQueryEvaluator eval = exp.Load(); XdmValue value = eval.Evaluate(); IEnumerator e = value.GetEnumerator(); while (e.MoveNext()) { Interval interval = new Interval(); var current = e.Current.ToString(); if (!current.Equals("")) // a revoir avec elio { MetadataAttributes geo = new MetadataAttributes("Geo", "Nominal", current, interval); ts.Add(geo); } } //ts.Reverse(); return(ts); }
public List <string> GetObjects(string query) { List <string> objects = new List <string>(); Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = BaseUri; XQueryExecutable exp = compiler.Compile(query); XQueryEvaluator eval = exp.Load(); XdmValue value = eval.Evaluate(); IEnumerator e = value.GetEnumerator(); while (e.MoveNext()) { objects.Add(e.Current.ToString()); } return(objects); }
/// <summary> /// This application uses the xslt file created from the /// original Word 2007 template document to transform xml data /// into a valid Open XML 2.0 Wordprocessing format. /// The application then updates the output document with the /// new content using the Open XML SDK version 2.0. /// </summary> static void Main(string[] args) { //Declare variables for file locations. string xmlDocxFile = @".\mydoc.xml"; string xmlResult = @".\mydoc1.xml"; FileStream fs = new FileStream(xmlDocxFile, FileMode.OpenOrCreate); XQueryCompiler compiler = new Processor().NewXQueryCompiler(); //bug on saxon's end... sounds stupid but force add base URI for the current location string directory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName + '\\'; string uri = new Uri(directory).AbsoluteUri; compiler.BaseUri = uri; XQueryExecutable executable = compiler.Compile(fs); XQueryEvaluator evaluator = executable.Load(); XdmValue result = evaluator.Evaluate(); FileStream fStream = System.IO.File.Open(xmlResult, FileMode.OpenOrCreate, FileAccess.ReadWrite); XmlWriterSettings settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment, Indent = true }; XmlWriter writer = XmlWriter.Create(fStream, settings); try { writer.WriteRaw(result.ToString()); } catch (Exception e) { writer.Close(); throw e; } finally { writer.Close(); } }
public List <MetadataAttributes> GetSocial(string query) { List <MetadataAttributes> ts = new List <MetadataAttributes>(); Processor processor = new Processor(); XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = BaseUri; XQueryExecutable exp = compiler.Compile(query); XQueryEvaluator eval = exp.Load(); XdmValue value = eval.Evaluate(); IEnumerator e = value.GetEnumerator(); while (e.MoveNext()) { Interval interval = new Interval(); MetadataAttributes social = new MetadataAttributes("Social", "Nominal", e.Current.ToString(), interval); ts.Add(social); } return(ts); }
/** * Run a test case * * * @param testCase the test case element in the catalog * @param xpc the XPath compiler to be used for compiling XPath expressions against the catalog * @ */ protected override void runTestCase(XdmNode testCase, XPathCompiler xpc) { bool run = true; bool xpDependency = false; string hostLang; string langVersion; Spec specOpt = Spec.NULL; XPathCompiler xpath = driverProc.NewXPathCompiler(); string testCaseName = testCase.GetAttributeValue(new QName("name")); string testSetName = testCase.Parent.GetAttributeValue(new QName("name")); bool needSerializedResult = ((XdmAtomicValue)xpc.EvaluateSingle( "exists(./result//assert-serialization-error) or exists(./result//serialization-matches)", testCase)).GetBooleanValue(); bool needResultValue = true; if (needSerializedResult) { needResultValue = ((XdmAtomicValue)xpc.EvaluateSingle( "exists(./result//*[not(self::serialization-matches or self::assert-serialization-error or self::any-of or self::all-of)])", testCase)).GetBooleanValue(); } XdmNode alternativeResult = null; XdmNode optimization = null; hostLang = ((SpecAttr)spec.GetAttr()).sname; langVersion = ((SpecAttr)spec.GetAttr()).version; Environment env = getEnvironment(testCase, xpc); if (env == null) { notrun++; return; } env.xpathCompiler.BackwardsCompatible = false; env.processor.XmlVersion = (decimal)1.0; //test bool icuColCheck = net.sf.saxon.Version.platform.hasICUCollator(); bool icuNumCheck = net.sf.saxon.Version.platform.hasICUNumberer(); Console.WriteLine("ICUCol: " + (icuColCheck ? "true" : "false")); Console.WriteLine("ICUNum: " + (icuNumCheck ? "true" : "false")); //end of test foreach (XdmItem dependency in xpc.Evaluate("/*/dependency, ./dependency", testCase)) { string type = ((XdmNode)dependency).GetAttributeValue(new QName("type")); if (type == null) { // throw new IllegalStateException("dependency/@type is missing"); //TODO } string value = ((XdmNode)dependency).GetAttributeValue(new QName("value")); if (value == null) { //throw new IllegalStateException("dependency/@value is missing"); //TODO } if (type.Equals("spec")) { bool applicable = false; if (!value.Contains(((SpecAttr)spec.GetAttr()).sname)) { applicable = false; } else if (value.Contains(((SpecAttr)spec.GetAttr()).svname)) { applicable = true; } else if (((SpecAttr)spec.GetAttr()).svname.Equals("XQ30") && value.Contains("XQ10+")) { applicable = true; } else if (((SpecAttr)spec.GetAttr()).svname.Equals("XP30") && value.Contains("XP20+")) { applicable = true; } if (!applicable) { writeTestcaseElement(testCaseName, "n/a", "not" + ((SpecAttr)spec.GetAttr()).svname, spec); notrun++; return; } } if (langVersion.Equals("3.0")) { /* EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() { * public Set<string> getAvailableEnvironmentVariables() { * Set<string> strings = new HashSet<string>(); * strings.add("QTTEST"); * strings.add("QTTEST2"); * strings.add("QTTESTEMPTY"); * return strings; * } * * public string getEnvironmentVariable(string name) { * if (name.Equals("QTTEST")) { * return "42"; * } else if (name.Equals("QTTEST2")) { * return "other"; * } else if (name.Equals("QTTESTEMPTY")) { * return ""; * } else { * return null; * } * } * }; */ //TODO //env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); } if (type.Equals("feature") && value.Equals("xpath-1.0-compatibility")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; specOpt = Spec.XP30; } if (type.Equals("feature") && value.Equals("namespace-axis")) { hostLang = "XP"; langVersion = "3.0"; xpDependency = true; specOpt = Spec.XP30; } if (!dependencyIsSatisfied((XdmNode)dependency, env)) { println("*** Dependency not satisfied: " + ((XdmNode)dependency).GetAttributeValue(new QName("type"))); writeTestcaseElement(testCaseName, "n/a", "Dependency not satisfied", spec); run = false; notrun++; return; } } XdmNode exceptionElement; try{ exceptionElement = exceptionsMap[testCaseName]; } catch (Exception) { exceptionElement = null; } if (exceptionElement != null) { XdmItem config = xpath.EvaluateSingle("configuration", exceptionElement); string runAtt = exceptionElement.GetAttributeValue(new QName("run")); string reasonMsg = xpath.EvaluateSingle("reason", exceptionElement).ToString(); string reportAtt = exceptionElement.GetAttributeValue(new QName("report")); if (config != null) { XdmItem paramValue = xpath.EvaluateSingle("param[@name='not-unfolded' and @value='yes']/@name", config); if (unfolded && paramValue != null) { writeTestcaseElement(testCaseName, "notRun", reasonMsg, spec); notrun++; return; } } if ("false".Equals(runAtt)) { writeTestcaseElement(testCaseName, reportAtt, reasonMsg, spec); notrun++; return; } alternativeResult = (XdmNode)xpc.EvaluateSingle("result", exceptionElement); optimization = (XdmNode)xpc.EvaluateSingle("optimization", exceptionElement); } if (run && (specOpt == Spec.NULL || specOpt == spec)) { TestOutcome outcome = new TestOutcome(this); string exp = null; try { exp = xpc.Evaluate("if (test/@file) then unparsed-text(resolve-uri(test/@file, base-uri(.))) else string(test)", testCase).ToString(); } catch (Exception err) { println("*** Failed to read query: " + err.Message); outcome.SetException((DynamicError)err); } //noinspection ThrowableResultOfMethodCallIgnored if (outcome.GetException() == null) { if (hostLang.Equals("XP") || hostLang.Equals("XT")) { XPathCompiler testXpc = env.xpathCompiler; testXpc.XPathLanguageVersion = langVersion; testXpc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); testXpc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema"); testXpc.DeclareNamespace("map", "http://www.w3.org/2005/xpath-functions/map"); //testXpc.DeclareNamespace("math", NamespaceConstant.MATH); //testXpc.DeclareNamespace("Dictionary", NamespaceConstant.Dictionary_FUNCTIONS); try { XPathSelector selector = testXpc.Compile(exp).Load(); foreach (QName varName in env.params1.Keys) { selector.SetVariable(varName, env.params1[varName]); } if (env.contextItem != null) { selector.ContextItem = env.contextItem; } selector.InputXmlResolver = new TestUriResolver(env); if (env.unparsedTextResolver != null) { //selector.getUnderlyingXPathContext().setUnparsedTextURIResolver(env.unparsedTextResolver); //TODO } XdmValue result = selector.Evaluate(); outcome.SetPrincipalResult(result); } catch (Exception err) { println(err.Message); outcome.SetException(err); } } else if (hostLang.Equals("XQ")) { XQueryCompiler testXqc = env.xqueryCompiler; testXqc.XQueryLanguageVersion = langVersion; testXqc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); testXqc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema"); //testXqc.DeclareNamespace("math", NamespaceConstant.MATH); testXqc.DeclareNamespace("map", "http://www.w3.org/2005/xpath-functions/map"); // ErrorCollector errorCollector = new ErrorCollector(); testXqc.ErrorList = new ArrayList(); string decVars = env.paramDecimalDeclarations.ToString(); if (decVars.Length != 0) { int x = (exp.IndexOf("(:%DECL%:)")); if (x < 0) { exp = decVars + exp; } else { exp = exp.Substring(0, x) + decVars + exp.Substring(x + 13); } } string vars = env.paramDeclarations.ToString(); if (vars.Length != 0) { int x = (exp.IndexOf("(:%VARDECL%:)")); if (x < 0) { exp = vars + exp; } else { exp = exp.Substring(0, x) + vars + exp.Substring(x + 13); } } ModuleResolver mr = new ModuleResolver(xpc); mr.setTestCase(testCase); // testXqc.QueryResolver = mr;// .setModuleURIResolver(mr); //TODO testXqc.QueryResolver = mr; try { XQueryExecutable q = testXqc.Compile(exp); if (optimization != null) { // Test whether required optimizations have been performed XdmDestination expDest = new XdmDestination(); JConfiguration config = driverProc.Implementation; //ExpressionPresenter presenter = new ExpressionPresenter(config, expDest.getReceiver(config)); //q.getUnderlyingCompiledQuery().explain(presenter); //presenter.close(); XdmNode explanation = expDest.XdmNode; XdmItem optResult = xpc.EvaluateSingle(optimization.GetAttributeValue(new QName("assert")), explanation); if (((XdmAtomicValue)optResult).GetBooleanValue()) { println("Optimization result OK"); } else { println("Failed optimization test"); Serializer ser = new Serializer(); ser.SetOutputStream((Stream)System.Console.OpenStandardError()); driverProc.WriteXdmValue(explanation, ser); writeTestcaseElement(testCaseName, "fail", "Failed optimization assertions", spec); failures++; return; } } XQueryEvaluator selector = q.Load(); foreach (QName varName in env.params1.Keys) { selector.SetExternalVariable(varName, env.params1[varName]); } if (env.contextItem != null) { selector.ContextItem = env.contextItem; } selector.InputXmlResolver = env; //selector.InputXmlResolver = .SetURIResolver(new TestURIResolver(env)); //TODO if (env.unparsedTextResolver != null) { selector.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);// TODO } if (needSerializedResult) { StringWriter sw = new StringWriter(); Serializer serializer = new Serializer(); //env.processor.NewSerializer(sw); //TODO serializer.SetOutputWriter(sw); selector.Run(serializer); outcome.SetPrincipalSerializedResult(sw.ToString()); } if (needResultValue) { XdmValue result = selector.Evaluate(); outcome.SetPrincipalResult(result); } } catch (Exception err) { println("in TestSet " + testSetName + err.StackTrace); println(err.Message); outcome.SetException(err); outcome.SetErrorsReported((IList)testXqc.ErrorList); } } else { writeTestcaseElement(testCaseName, "notRun", "No processor found", spec); notrun++; return; } } if (env.resetAction != null) { env.resetAction.reset(env); } XdmNode assertion; if (alternativeResult != null) { assertion = (XdmNode)xpc.EvaluateSingle("*[1]", alternativeResult); } else { assertion = (XdmNode)xpc.EvaluateSingle("result/*[1]", testCase); } if (assertion == null) { println("*** No assertions found for test case " + testCaseName); writeTestcaseElement(testCaseName, "disputed", "No assertions in test case", spec); feedback.Feedback(successes, failures++, total); return; } XPathCompiler assertXpc = env.processor.NewXPathCompiler(); assertXpc.XPathLanguageVersion = "3.1"; assertXpc.DeclareNamespace("fn", "http://www.w3.org/2005/xpath-functions"); assertXpc.DeclareNamespace("xs", "http://www.w3.org/2001/XMLSchema"); assertXpc.DeclareNamespace("math", "http://www.w3.org/2005/xpath-functions/math"); assertXpc.DeclareNamespace("MAP_FUNCTIONS", "http://www.w3.org/2005/xpath-functions/map"); assertXpc.DeclareVariable(new QName("result")); bool b = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertXpc, xpc, debug); if (b) { //println("OK"); writeTestcaseElement(testCaseName, "pass", null, spec); feedback.Feedback(successes++, failures, total); } else { if (outcome.IsException()) { XdmItem expectedError = xpc.EvaluateSingle("result//error/@code", testCase); if (expectedError == null) { // if (debug) { // outcome.getException().printStackTrace(System.out); // } writeTestcaseElement(testCaseName, "fail", "Expected success, got ", spec); println("*** fail, result " + outcome.GetException() + " Expected success."); feedback.Feedback(successes, failures++, total); } else { writeTestcaseElement(testCaseName, "wrongError", "Expected error:" + expectedError.ToString() + ", got " + outcome.GetErrorCode().LocalName, spec); println("*** fail, result " + outcome.GetErrorCode().LocalName + " Expected error:" + expectedError.ToString()); wrongErrorResults++; feedback.Feedback(successes++, failures, total); } } else { writeTestcaseElement(testCaseName, "fail", "Wrong results, got " + truncate(outcome.Serialize(assertXpc.Processor, outcome.GetPrincipalResultDoc())), spec); feedback.Feedback(successes, failures++, total); if (debug) { try { println("Result:"); driverProc.WriteXdmValue(outcome.GetPrincipalResult(), driverSerializer); println("<======="); } catch (Exception err) { } //println(outcome.getResult()); } else { println("*** fail (use -debug to show actual result)"); //failures++; } } } } }
private void compareModule(string paperName, string compareName) { Processor pr = new Processor(); XQueryCompiler xqc = pr.NewXQueryCompiler(); string comparePath = "Papers\\" + paperName + "\\" + compareName + "_rule.xml"; string curPath = Directory.GetCurrentDirectory(); string configPath = curPath + "\\Config\\" + compareName + ".config"; string errPath = "Papers\\" + paperName + "\\" + compareName + "_err.xml"; XmlDocument doc = new XmlDocument(); doc.Load(comparePath); XmlElement root = doc.DocumentElement; XmlNodeList ruleNodes = root.GetElementsByTagName("rule"); XmlDocument errDoc = new XmlDocument(); XmlNode node = errDoc.CreateXmlDeclaration("1.0", "utf-8", "");//创建类型声明节点 errDoc.AppendChild(node); XmlNode err = errDoc.CreateElement("error");//创建根节点 foreach (XmlNode xrule in ruleNodes) { string rule = xrule.InnerText; XQueryExecutable xqe = xqc.Compile(rule); XQueryEvaluator xqev = xqe.Load(); if (!paperName.Contains("#")) { XdmValue result = xqev.Evaluate(); //对比结果 foreach (XdmItem r in result) { string rstr = r.ToString(); string[] rarr = rstr.Split('/'); string errstr = "for $x in doc(\"" + configPath + "\")/conf/"; if (rarr.Length == 3) { errstr += "module[@tag=" + "\"" + rarr[0] + "\"]/"; errstr += "section[@tag=" + "\"" + rarr[1] + "\"]/"; errstr += "item[@tag=" + "\"" + rarr[2] + "\"]/error-msg/text() return $x"; } else { errstr += "module[@tag=" + "\"" + rarr[0] + "\"]/"; errstr += "section[@tag=" + "\"" + rarr[1] + "\"]/"; errstr += "part[@tag=" + "\"" + rarr[2] + "\"]/"; errstr += "item[@tag=" + "\"" + rarr[3] + "\"]/error-msg/text() return $x"; } XmlElement err_rule = errDoc.CreateElement("err-rule"); //string errstr = rstr; err_rule.InnerText = errstr; err.AppendChild(err_rule); } errDoc.AppendChild(err); errDoc.Save(errPath); } else { errDoc.AppendChild(err); errDoc.Save(errPath); } } }