Beispiel #1
0
 private bool AssertType(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc)
 {
     if (IsException())
     {
         return(false);
     }
     else
     {
         XPathSelector s = assertXpc.Compile("$result instance of " + assertion.StringValue).Load();
         s.SetVariable(new QName("result"), result.value);
         return(((XdmAtomicValue)s.EvaluateSingle()).GetBooleanValue());
     }
 }
Beispiel #2
0
    private IList getCollection(XdmNode collectionNode)
    {
        ArrayList   list = new ArrayList(10);
        IEnumerator e    = collectionNode.EnumerateAxis(
            XdmAxis.Child, new QName(testURI, "input-document"));

        while (e.MoveNext())
        {
            XdmNode node = (XdmNode)e.Current;
            list.Add(new Uri(testSuiteDir + "/TestSources/" + node.StringValue + ".xml"));
        }
        return(list);
    }
Beispiel #3
0
        private XdmNode getLinkedDocument(XdmNode element, Processor processor, bool validate)
        {
            String          href    = element.GetAttributeValue(xlinkHref);
            DocumentBuilder builder = processor.NewDocumentBuilder();
            Uri             target  = new Uri(element.BaseUri, href);

            builder.IsLineNumbering = true;
            if (validate)
            {
                builder.SchemaValidationMode = SchemaValidationMode.Strict;
            }
            return(builder.Build(target));
        }
Beispiel #4
0
 private bool assertDeepEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc)
 {
     if (IsException())
     {
         return(false);
     }
     else
     {
         XPathSelector s = assertXpc.Compile("deep-equal($result , (" + assertion.StringValue + "))").Load();
         s.SetVariable(new QName("result"), result.value);
         return(((XdmAtomicValue)s.Evaluate()).GetBooleanValue());
     }
 }
Beispiel #5
0
        public void RunXPath(List <QueryClass> Xqueries, string sourceFolder)
        {
            Dictionary <string, XmlDocument> sources = new Dictionary <string, XmlDocument>();

            foreach (XML_Query q in Xqueries)
            {
                if (q.JobEnabled.Equals("1") || q.JobEnabled.Equals("2") || q.JobEnabled.Equals("3"))
                {
                    string xmlFileName = Path.Combine(sourceFolder, q.Source);
                    Console.WriteLine("Source: " + q.Source + ", XML File: " + xmlFileName);

                    Processor processor = new Processor();

                    XmlDocument inputDoc = new XmlDocument();

                    if (!sources.ContainsKey(q.Source))
                    {
                        XmlDocument newDoc = new XmlDocument();
                        newDoc.Load(xmlFileName);
                        sources.Add(q.Source, newDoc);
                    }
                    inputDoc = sources[q.Source];

                    XdmNode xmlDoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(inputDoc));

                    XPathCompiler xPathCompiler = processor.NewXPathCompiler();

                    string nameSpace    = inputDoc.DocumentElement.NamespaceURI;
                    string nameSpaceXsi = inputDoc.DocumentElement.GetNamespaceOfPrefix("xsi");

                    xPathCompiler.DeclareNamespace("", nameSpace);
                    xPathCompiler.DeclareNamespace("xsi", nameSpaceXsi);

                    string query = q.Query;

                    try
                    {
                        OnProgressUpdate?.Invoke(q.JobId);
                        string result = xPathCompiler.Evaluate(query, xmlDoc).ToString();

                        q.Result = result.Replace("\"", "");
                    }
                    catch (Exception e)
                    {
                        OnProgressUpdate?.Invoke("ERROR: " + q.JobId);
                        q.Result = "ERROR 1, unable to compile: " + q.Query;
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
Beispiel #6
0
        public override int runCommand(XdmNode node)
        {
            Speech sp   = Speech.instance;
            string text = "";

            if (getProperties().ContainsKey("select"))
            {
                string   exp  = getProperties()["select"];
                XdmValue iter = XMLContext.instance.xpath.Evaluate(exp, node);
                foreach (XdmItem child in iter)
                {
                    /*
                     * switch (child.NodeType)
                     * {
                     *  case XmlNodeType.Element:
                     *      text += child.InnerText;
                     *      break;
                     *  case XmlNodeType.Text:
                     *      text += child.InnerText;
                     *      break;
                     * }
                     */
                    if (child.IsNode())
                    {
                        text += ((XdmNode)child).StringValue;
                    }
                    else if (child.IsAtomic())
                    {
                        text += child.Simplify.ToString();
                    }
                    //
                }
                logger.log("Text Select " + text);
            }
            else if (getProperties().ContainsKey("@text"))
            {
                text = getProperties()["@text"];
                //logger.log("Replacers count " + EventContext.instance.replacers.Count);
                foreach (Replacer rp in EventContext.instance.replacers)
                {
                    text = rp.Replace(text);
                }
            }

            if (text != null && text.Length > 0)
            {
                sp.speak(text);
            }
            return(0);
        }
Beispiel #7
0
        void createHtmlFromXsl()
        {
            string resultDoc = projSettings.DestinationPath + projSettings.DocHtmlFileName;

            if (projSettings.StyleName == "OrteliusXml")
            {
                resultDoc = projSettings.DestinationPath + "/orteliusXml.xml";
            }
            string xmlDoc = projSettings.DestinationPath + projSettings.DocXmlFileName;
            string xslDoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/styles/" + projSettings.StyleName + ".xsl";

            try
            {
                Processor processor                 = new Processor();
                System.IO.StreamReader reader       = new System.IO.StreamReader(xmlDoc, System.Text.Encoding.UTF8);
                System.IO.TextWriter   stringWriter = new System.IO.StringWriter();

                stringWriter.Write(reader.ReadToEnd());
                stringWriter.Close();

                reader.Close();

                System.IO.TextReader     stringReader = new System.IO.StringReader(stringWriter.ToString());
                System.Xml.XmlTextReader reader2      = new System.Xml.XmlTextReader(stringReader);
                reader2.XmlResolver = null;

                // Load the source document
                XdmNode input = processor.NewDocumentBuilder().Build(reader2);

                // Create a transformer for the stylesheet.
                XsltTransformer transformer = processor.NewXsltCompiler().Compile(new System.Uri(xslDoc)).Load();
                transformer.InputXmlResolver = null;

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer
                Serializer serializer = new Serializer();

                serializer.SetOutputFile(resultDoc);

                // Transform the source XML to System.out.
                transformer.Run(serializer);
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
                systemSvar += "Error in xslt rendering:\r\n" + e.ToString();
            }
        }
Beispiel #8
0
 private bool assertEq(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc)
 {
     if (IsException())
     {
         return(false);
     }
     else
     {
         XPathSelector s = assertXpc.Compile("$result eq " + assertion.StringValue).Load();
         s.SetVariable(new QName("result"), result.value);
         XdmAtomicValue item = (XdmAtomicValue)s.EvaluateSingle();
         return(item != null && item.GetBooleanValue());
     }
 }
Beispiel #9
0
        /// <summary>
        /// Perform XQuery <paramref name="query"/> on XML document at <paramref name="input"/> using Saxon API.
        /// </summary>
        /// <param name="input">A valid XML document.</param>
        /// <param name="query">An XQuery query.</param>
        /// <returns>Returns the results of the <paramref name="query"/> as an XmlDocument.</returns>
        public static XmlDocument PerformQuery(XmlDocument input, string query)
        {
            var              processor  = new Processor();
            XdmNode          inputXml   = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));
            XQueryCompiler   compiler   = processor.NewXQueryCompiler();
            XQueryExecutable executable = compiler.Compile(query);
            XQueryEvaluator  evaluator  = executable.Load();

            evaluator.ContextItem = inputXml;
            var domOut = new DomDestination();

            evaluator.Run(domOut);
            return(domOut.XmlDocument);
        }
Beispiel #10
0
        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>
        /// you shoud have xml subfolder with camt2Html.xsl and one or more iso20022 xml bank statements files
        /// app will transform all xml to BetterBankStatements.html
        /// simply edit xls file to change html result
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                string myPath     = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                string sourceFile = myPath + @"\xml\camt2Html.xsl";
                string stylesheet = myPath + @"\xml\camt2Html.xsl";
                string outputFile = myPath + @"\xml\BetterBankStatements.html";
                try
                {
                    // Create a Processor instance.
                    Processor processor = new Processor();

                    // Load the source document
                    DocumentBuilder builder = processor.NewDocumentBuilder();
                    builder.BaseUri = new Uri(sourceFile);

                    XdmNode input = builder.Build(File.OpenRead(sourceFile));

                    // Create a transformer for the stylesheet.
                    XsltCompiler compiler = processor.NewXsltCompiler();
                    compiler.BaseUri = new Uri(stylesheet);
                    Xslt30Transformer transformer = compiler.Compile(File.OpenRead(stylesheet)).Load30();

                    // Set the root node of the source document to be the global context item
                    transformer.GlobalContextItem = input;

                    // Create a serializer, with output to the standard output stream
                    Serializer serializer = processor.NewSerializer();
                    serializer.SetOutputStream(new FileStream(outputFile, FileMode.Create, FileAccess.Write));

                    // Transform the source XML and serialize the result to the output file.
                    transformer.ApplyTemplates(input, serializer);

                    Console.WriteLine("\nOutput written to " + outputFile + "\n");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nError:" + ex.Message + "\n");
                    Console.WriteLine(ex.StackTrace + "\n");
                }
            }
            else
            {
                Console.WriteLine("izpiski (xml iso20022) morajo bit v podmapi xml skupaj z camt2Html.xsl");
                Console.WriteLine("retultat bo izpiski.html");
            }
            Console.ReadKey();
        }
Beispiel #12
0
        public static XdmNode FirstElementOrSelf(this XdmNode value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if (value.NodeKind == XmlNodeType.Element)
            {
                return(value);
            }

            return(((IXdmEnumerator)value.EnumerateAxis(XdmAxis.Child)).AsNodes().SingleOrDefault(n => n.NodeKind == XmlNodeType.Element)
                   ?? value);
        }
Beispiel #13
0
        //run an XSLT transform.
        //transformFile is the name of the .xsl to run;
        //path is usually tools directory (be sure to include final slash in passed string)
        //takes two paramaters and corresponding values; use empty strings if not needed
        static public XmlDocument performTransformWith2Params(XmlDocument inDOM, string path, string transformFile, string param1Name, string param1Value, string param2Name, string param2Value)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document, building a tree
            XmlNode node  = inDOM;
            XdmNode input = processor.NewDocumentBuilder().Build(node);

            // Compile the stylesheet
            XsltExecutable exec = processor.NewXsltCompiler().Compile(new XmlTextReader(path.Replace("Program Files", "PROGRA~1") + transformFile));

            // Create a transformer
            XsltTransformer transformer = exec.Load();

            string xdmToolsPath = "file:/" + path.Replace("\\", "/").Replace(" ", "%20");

            // Run it once
            // Set parameters
            transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false));
            //following may be needed if xslt itself needs to find other files
            transformer.SetParameter(new QName("", "", "localBaseUri"), new XdmAtomicValue(xdmToolsPath.Replace("Program%20Files", "PROGRA~1")));
            //optionally add another parameter
            if (!String.IsNullOrEmpty(param1Name))
            {
                transformer.SetParameter(new QName("", "", param1Name), new XdmAtomicValue(param1Value));
            }
            //and another param
            if (!String.IsNullOrEmpty(param2Name))
            {
                transformer.SetParameter(new QName("", "", param2Name), new XdmAtomicValue(param2Value));
            }

            transformer.InitialContextNode = input;
            XdmDestination results = new XdmDestination();

            transformer.Run(results);

            XmlDocument resultXmlDoc = new XmlDocument();

            resultXmlDoc.LoadXml(results.XdmNode.OuterXml);
            XmlDeclaration declaration = resultXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            resultXmlDoc.PrependChild(declaration);

            // return the result
            return(resultXmlDoc);
        }
Beispiel #14
0
        private bool assertPermutation(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc)
        {
            // TODO: extend this to handle nodes (if required)
            if (IsException())
            {
                return(false);
            }
            else
            {
                return(true);

                try {
                    int expectedItems         = 0;
                    HashSet <string> expected = new HashSet <string>();
                    XPathSelector    s        = assertXpc.Compile("(" + assertion.StringValue + ")").Load();
                    s.SetVariable(new QName("result"), result.value); // not used, but we declared it
                    JCodepointCollator collator = JCodepointCollator.getInstance();
                    //JXPathContext context =  new JXPathContextMajor(stringValue.EMPTY_string, assertXpc.getUnderlyingStaticContext().getConfiguration());
                    foreach (XdmItem item in s)
                    {
                        expectedItems++;
                        XdmValue value = (XdmValue)item.Simplify;
                        // value.Simplify.

                        /*  Object comparable = value.isNaN() ?
                         *        AtomicSortComparer.COLLATION_KEY_NaN :
                         *        value.getXPathComparable(false, collator, context);
                         * expected.Add(comparable);*/
                    }
                    int actualItems = 0;
                    foreach (XdmItem item in GetPrincipalResult())
                    {
                        actualItems++;
                        XdmValue value = (XdmValue)item.Simplify;

                        /*Object comparable = value.isNaN() ?
                         *      AtomicSortComparer.COLLATION_KEY_NaN :
                         *      value.getXPathComparable(false, collator, context); */
                        //   if (!expected.Contains(comparable)) {
                        return(false);
                        // }
                    }
                    return(actualItems == expectedItems);
                } catch (DynamicError) {
                    return(false);
                }
            }
        }
        protected override void createGlobalEnvironments(XdmNode catalog, XPathCompiler xpc)
        {
            Environment environment = null;
            Environment defaultEnv  = null;

            try
            {
                defaultEnv = localEnvironments["default"];
            }
            catch (Exception) { }
            foreach (XdmItem env in xpc.Evaluate("//environment", catalog))
            {
                environment = Environment.processEnvironment(this, xpc, env, globalEnvironments, defaultEnv);
            }
            //buildDependencyMap(driverProc, environment);
        }
Beispiel #16
0
        public bool TestAssertion(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)
        {
            try {
                string tag     = assertion.NodeName.LocalName;
                bool   success = TestAssertion2(assertion, result, assertXpc, catalogXpc, debug);
                if (debug && !("all-of".Equals(tag)) && !("any-of".Equals(tag)))
                {
                    driver.println("Assertion " + tag + " (" + assertion.StringValue + ") " + (success ? " succeeded" : " failed"));
                    if (tag.Equals("error"))
                    {
                        if (IsException())
                        {
                            bool b = compareExpectedError(assertion);
                            if (b)
                            {
                                driver.println("Returned error as expected");
                            }
                            else
                            {
                                driver.println(wrongError);
                            }
//                        QName code = getException().getErrorCode();
//                        if (code == null) {
//                            actual = "error with no code";
//                        } else {
//                            actual = code.getLocalName();
//                        }
                        }
                        else
                        {
                            driver.println("Expected exception " + assertion.GetAttributeValue(new QName("code")) + "; got success");
                        }
//                    driver.println("Expected exception " + assertion.getAttributeValue(new QName("code")) +
//                            ", got " + actual);
                    }
                }
                if (!success && wrongError != null)
                {
                    // treat getting the wrong error as a pass
                    success = true;
                }
                return(success);
            } catch (Exception e) {
                System.Console.WriteLine(e.StackTrace); //To change body of catch statement use File | Settings | File Templates.
                return(false);
            }
        }
Beispiel #17
0
 public override int runCommand(XdmNode node)
 {
     if (selectParam != null && selectParam.Length > 0)
     {
         //XmlElement selectNode = (XmlElement)node.SelectSingleNode(selectParam);
         XdmItem selectNode = XMLContext.instance.xpath.EvaluateSingle(selectParam, node);
         if (selectNode != null && selectNode.IsNode())
         {
             runChilds((XdmNode)selectNode);
         }
     }
     else
     {
         logger.log("Check \"select\" parameter at Switch command!");
     }
     return(0);
 }
    /// <summary>
    /// Compare two files using the XML comparator.
    /// </summary>
    /// <param name="actual">Filename of results obtained in this test run</param>
    /// <param name="gold">Filename of reference results (expected results)</param>
    /// <returns>true if the results are the same</returns>

    private bool compareXML(String actual, String gold)
    {
        try {
            XdmNode       doc1 = processor.NewDocumentBuilder().Build(new Uri(actual));
            XdmNode       doc2 = processor.NewDocumentBuilder().Build(new Uri(gold));
            XPathSelector t    = compareDocuments.Load();
            t.SetVariable(new QName("", "actual"), doc1);
            t.SetVariable(new QName("", "gold"), doc2);
            t.SetVariable(new QName("", "debug"), new XdmAtomicValue(debug));
            XdmAtomicValue result = (XdmAtomicValue)t.EvaluateSingle();
            return((bool)result.Value);
        } catch (Exception e) {
            Console.WriteLine(e.StackTrace);
            Console.WriteLine("***" + e.Message);
            return(false);
        }
    }
Beispiel #19
0
        public override void TreeToTreeTransform()
        {
            XsltTransformer transformer = stylesheet.Load();

            if (sourceDocument != null)
            {
                transformer.InitialContextNode = sourceDocument;
            }
            else
            {
                transformer.InitialTemplate = new QName("main");
            }
            XdmDestination destination = new XdmDestination();

            transformer.Run(destination);
            resultDocument = destination.XdmNode;
        }
Beispiel #20
0
        public void TestMethod1()
        {
            Uri baseuri = new Uri(@"D:\Develop\ehrsfm_profile\trunk\Saxon.Tests\");

            // Create a Processor instance.
            Processor    processor = new Processor();
            XsltCompiler compiler  = processor.NewXsltCompiler();

            compiler.ErrorList = new List <StaticError>();
            DocumentBuilder builder = processor.NewDocumentBuilder();

            //builder.XmlResolver = new UserXmlResolver();

            try
            {
                // Create a transformer for the stylesheet.
                XsltTransformer transformer = compiler.Compile(new Uri(baseuri, @"XSLTFile1.xslt")).Load();

                // Load the source document
                XdmNode input = builder.Build(new Uri(baseuri, @"XMLFile1.xml"));

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer, with output to the standard output stream
                Serializer serializer = new Serializer();
                //StringWriter output = new StringWriter();
                //serializer.SetOutputWriter(output);
                serializer.SetOutputFile(@"D:\Develop\ehrsfm_profile\trunk\Saxon.Tests\XMLFile1.output.xml");

                // Transform the source XML and serialize the result document
                transformer.Run(serializer);

                //Console.WriteLine(output.ToString());
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var error in compiler.ErrorList)
                {
                    sb.AppendLine(error.ToString());
                }
                Assert.Fail(sb.ToString());
            }
        }
        public string InvoiceTransform(string code, string code2)
        {
            string invoiceHtml = String.Empty;

            if (code == "" || code2 == "")
            {
                Response.Write("<script lang='JavaScript'>alert('Dosyaları Yüklemeden Kaydetme İşlemi Gerçekleşmez');</script>");
            }
            else
            {
                //textarealardaki değişikliklerini hafızaya kaydet
                MemoryStream Xml = new MemoryStream(Encoding.UTF8.GetBytes(code));
                Xml.Write(System.Text.Encoding.UTF8.GetBytes(code), 0, code.Length);
                ViewBag.mesaj = code;


                MemoryStream Xslt = new MemoryStream(Encoding.UTF8.GetBytes(code2));
                Xslt.Write(System.Text.Encoding.UTF8.GetBytes(code2), 0, code2.Length);
                ViewBag.mesaj2 = code2;

                localXmlString  = ViewBag.mesaj;
                localXsltString = ViewBag.mesaj2;


                Processor       xsltProcessor   = new Processor();
                DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();
                documentBuilder.BaseUri = new Uri("file://");
                XdmNode xdmNode = documentBuilder.Build(new StringReader(code));

                XsltCompiler    xsltCompiler    = xsltProcessor.NewXsltCompiler();
                XsltExecutable  xsltExecutable  = xsltCompiler.Compile(new StringReader(code2));
                XsltTransformer xsltTransformer = xsltExecutable.Load();
                xsltTransformer.InitialContextNode = xdmNode;

                using (StringWriter stringWriter = new StringWriter())
                {
                    Serializer serializer = new Serializer();
                    serializer.SetOutputWriter(stringWriter);
                    xsltTransformer.Run(serializer);
                    ViewBag.cikti = stringWriter;
                    invoiceHtml   = stringWriter.ToString();
                }
            }
            return(invoiceHtml);
        }
Beispiel #22
0
        /**
         * Saxon: Safe when Whitelisting on XQuery Expression Example
         * Proves that Saxon is safe from injection when whitelisting the XQuery expression
         */
        protected void Page_Load(object sender, EventArgs e)
        {
            bool expectedSafe = false;

            try
            {
                // parse the XML
                Processor       processor = new Processor(false);
                DocumentBuilder doc       = processor.newDocumentBuilder();
                XdmNode         node      = doc.build(new StreamSource(appPath + "/resources/students.xml"));

                // query the XML
                string query;
                if (Request.QueryString["payload"].Contains("\"") || Request.QueryString["payload"].Contains(";"))
                {
                    PrintResults(expectedSafe, new List <string>());
                    throw new InvalidParameterException("First Name parameter must not contain quotes or semicolons");
                }
                else
                {
                    query = "for $s in //Students/Student " +
                            "where $s/FirstName = \"" + Request.QueryString["payload"] + "\" " +
                            "return $s";    // safe in here!
                }
                XQueryCompiler   xqComp = processor.newXQueryCompiler();
                XQueryExecutable xqExec = xqComp.compile(query);
                XQueryEvaluator  xqEval = xqExec.load();
                xqEval.setContextItem(node);
                xqEval.evaluate();

                // interpret the result of the query
                List <string> resultList = new List <string>();
                foreach (XdmValue value in xqEval)
                {
                    resultList.Add(value.ToString());
                }

                // print the results on the query
                PrintResults(expectedSafe, resultList);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }
Beispiel #23
0
        protected override void createGlobalEnvironments(XdmNode catalog, XPathCompiler xpc)
        {
            Environment environment = null;

            Environment defaultEnv = null;

            try
            {
                defaultEnv = localEnvironments["default"];
            }
            catch (Exception) { }
            foreach (XdmNode env in catalog.Select(Steps.Descendant("environment")))
            {
                environment = Environment.processEnvironment(
                    this, xpc, env, globalEnvironments, defaultEnv);
            }
            buildDependencyDictionary(driverProc, environment);
        }
Beispiel #24
0
        /// <summary>
        /// Compare two XML files
        /// </summary>
        /// <param name="actual">The URI of the first file</param>
        /// <param name="gold">The URI of the second file</param>
        /// <returns></returns>

        private String compareXML(String actual, String gold)
        {
            try
            {
                if (xmlComparer == null)
                {
                    xmlComparer = processor.NewXsltCompiler().Compile(new Uri(comparerDir + "/compare.xsl"));
                }
                XdmNode doc1 = processor.NewDocumentBuilder().Build(new Uri(actual));
                XdmNode doc2 = processor.NewDocumentBuilder().Build(new Uri(gold));
                return(compareDocs(doc1, doc2));
            }
            catch (Exception e)
            {
                Console.WriteLine("***" + e.Message);
                return("XML comparison failure: " + e.Message);
            }
        }
Beispiel #25
0
        public override void Close()
        {
            if (this.currentState == WriteState.Closed)
            {
                return;
            }

            try {
                this.builder.endDocument();
                this.builder.close();
            } catch {
                this.currentState = WriteState.Error;
                throw;
            }

            this.currentState = WriteState.Closed;
            this.document     = (XdmNode)XdmValue.Wrap(this.builder.getCurrentRoot());
        }
Beispiel #26
0
        static bool NamespaceScopeOk(XdmNode nsNode, XPathNamespaceScope namespaceScope)
        {
            switch (namespaceScope)
            {
            case XPathNamespaceScope.All:
                return(true);

            case XPathNamespaceScope.ExcludeXml:

                return(nsNode.NodeName == null ||
                       nsNode.NodeName.LocalName != "xml");

            case XPathNamespaceScope.Local:

                if (nsNode.NodeName != null &&
                    nsNode.NodeName.LocalName == "xml")
                {
                    return(false);
                }

                XdmNode parentNode = nsNode.Parent.Parent;

                if (parentNode != null)
                {
                    IEnumerator parentScope = parentNode.EnumerateAxis(XdmAxis.Namespace);

                    while (parentScope.MoveNext())
                    {
                        XdmNode pNsNode = (XdmNode)parentScope.Current;

                        if (nsNode.NodeName == pNsNode.NodeName &&
                            nsNode.StringValue == pNsNode.StringValue)
                        {
                            return(false);
                        }
                    }
                }

                return(true);

            default:
                throw new ArgumentOutOfRangeException("namespaceScope");
            }
        }
Beispiel #27
0
        public override void TreeToTreeTransform()
        {
            XsltTransformer transformer = stylesheet.Load();

            processor.SetProperty(net.sf.saxon.lib.FeatureKeys.SCHEMA_VALIDATION_MODE, schemaAware ? "strict" : "strip");
            //transformer.SchemaValidationMode = SchemaValidationMode.Strict;   // not working in 9.5.1.5: see bug 2062
            if (sourceDocument != null)
            {
                transformer.InitialContextNode = sourceDocument;
            }
            else
            {
                transformer.InitialTemplate = new QName("main");
            }
            XdmDestination destination = new XdmDestination();

            transformer.Run(destination);
            resultDocument = destination.XdmNode;
        }
Beispiel #28
0
 public override int runCommand(XdmNode node)
 {
     if (selectParam != null && selectParam.Length > 0)
     {
         XdmValue nodes = XMLContext.instance.xpath.Evaluate(selectParam, node);
         if (nodes.Count > 0)
         {
             foreach (XdmNode element in nodes)
             {
                 runChilds(element);
             }
         }
     }
     else
     {
         logger.log("Check \"select\" parameter at ForEach command!");
     }
     return(0);
 }
Beispiel #29
0
        public bool compareExpectedError(XdmNode assertion)
        {
            string expectedError = assertion.GetAttributeValue(new QName("code"));
            QName  expectedErrorQ;

            if (expectedError.Equals("*"))
            {
                expectedErrorQ = null;
            }
            else if (expectedError.StartsWith("Q{"))
            {
                expectedErrorQ = QName.FromEQName(expectedError);
            }
            else
            {
                expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
            }
            //noinspection ThrowableResultOfMethodCallIgnored
            bool ok = (expectedError.Equals("*") ||
                       (GetErrorCode() != null &&
                        GetErrorCode().LocalName.Equals(expectedErrorQ.LocalName)) ||
                       (HasReportedError(new QName(expectedError))));

            if (ok)
            {
                wrongError = null;
            }
            else if (expectedErrorQ != null && errorsReported != null && errorsReported.Count != 0)
            {
                JFastStringBuffer fsb = new JFastStringBuffer(100);
                fsb.append("Expected ");
                fsb.append(expectedErrorQ.LocalName);
                fsb.append("; got ");
                foreach (QName e in errorsReported)
                {
                    fsb.append(e.LocalName);
                    fsb.append("|");
                }
                fsb.setLength(fsb.length() - 1);
                wrongError = fsb.ToString();
            }
            return(ok);
        }
Beispiel #30
0
        static void Transforma()
        {
            /* cria uma instancia do processador */
            Processor processor = new Processor();

            /* carrega o documento a ser processado */
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(pathXtm));

            /* cria o transformer com o stylesheet informado */
            Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(new Uri(pathXsl)).Load30();

            transformer.BaseOutputURI = "file:///" + Directory.GetCurrentDirectory().Replace("\\", "/");
            //String outfile = Directory.GetCurrentDirectory() + "\\Saida";
            Serializer serializer = processor.NewSerializer();

            //serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));

            transformer.ApplyTemplates(input, serializer);
        }