Example #1
0
        static void Main(string[] args)
        {
            if ( args.Length < 2)
            {
                Console.Error.WriteLine("Syntax: demo <path-to-xml-file> <xpath-expression> [<num-iterations(default={0})>]", numIters);
                return;
            }

            var file = args[0];
            var xpath = args[1];

            if ( args.Length > 2)
            {
                numIters = int.Parse(args[2]);
            }

            Console.WriteLine("Loading {0}", file);

            var proc = new Processor();

            var ms_xp = System.Xml.XPath.XPathExpression.Compile(xpath);

            var xpc = proc.NewXPathCompiler();
            var xpe = xpc.Compile(xpath);
            var sel = xpe.Load();

            var doc = XDocument.Load(file);
            var ctx = proc.Wrap(doc);
            sel.ContextItem = ctx;

            var nt = new NameTable();
            XmlDocument xd = new XmlDocument(nt);
            xd.Load(file);

            var ctxXmlDoc = proc.NewDocumentBuilder().Wrap(xd);

            Console.WriteLine("Evaluating {0}", xpath);

            Time(() => Saxon(sel), "XDoc (Saxon)");
            Time(() => Native(ms_xp, doc), "XDoc (Native)");

            sel.ContextItem = ctxXmlDoc;

            Time(() => Saxon(sel), "XmlDoc (Saxon)");
            Time(() => Native(ms_xp, xd), "XmlDoc (Native)");
        }
        /// <summary>
        /// Load the XSLT file
        /// </summary>
        public void Load(string filename, bool profilingEnabled = false)
        {
            //register our eval() function
            processor = new Processor();
            processor.RegisterExtensionFunction(new SaxonEvaluate(processor.NewXPathCompiler()));

            //tracing
            if (profilingEnabled)
            {
                var profile = new TimingTraceListener();
                processor.Implementation.setTraceListener(profile);
                processor.Implementation.setLineNumbering(true);
                processor.Implementation.setCompileWithTracing(true);
                processor.Implementation.getDefaultXsltCompilerInfo().setCodeInjector(new TimingCodeInjector());
                profile.setOutputDestination(new java.io.PrintStream("profile.html"));
            }

            //capture the error information
            var compiler = processor.NewXsltCompiler();
            compiler.ErrorList = errorList;

            //compile the stylesheet
            var relativeFilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename);
            try
            {
                var exec = compiler.Compile(XmlTextReader.Create(relativeFilename));

                //capture xsl:message output
                transform = exec.Load();
                transform.MessageListener = new SaxonMessageListener();
            }
            catch (Exception)
            {
                foreach (StaticError err in compiler.ErrorList)
                {
                    log.ErrorFormat("{0} ({1}, line {2})", err, err.ModuleUri, err.LineNumber);
                }
                throw;
            }
        }
    /**
    * 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.");
    }
Example #4
0
        /// <summary>
        /// Execute an XPath expression that throws a dynamic error, and catch the error
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Create the XPath expression.
            XPathCompiler compiler = processor.NewXPathCompiler();
            compiler.AllowUndeclaredVariables = true;
            XPathExecutable expression = compiler.Compile("1 + unknown()");
            XPathSelector selector = expression.Load();

            // Evaluate the XPath expression
            Console.WriteLine(selector.EvaluateSingle().ToString());
        }
Example #5
0
        /// <summary>
        /// Execute an XPath expression that throws a dynamic error
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Create the XPath expression.
            XPathCompiler compiler = processor.NewXPathCompiler();
            compiler.AllowUndeclaredVariables = true;
            XPathExecutable expression = compiler.Compile("$a gt $b");
            XPathSelector selector = expression.Load();

            // Set the values of the variables
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(10));
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue("Paris"));

            // Evaluate the XPath expression
            Console.WriteLine(selector.EvaluateSingle().ToString());
        }
Example #6
0
        /// <summary>
        /// Run a transformation: simplest possible script
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Create the XPath expression.
            XPathCompiler compiler = processor.NewXPathCompiler();
            compiler.DeclareVariable(new QName("", "a"));
            compiler.DeclareVariable(new QName("", "b"));
            XPathSelector selector = compiler.Compile("$a + $b").Load();

            // Set the values of the variables
            selector.SetVariable(new QName("", "a"), new XdmAtomicValue(2));
            selector.SetVariable(new QName("", "b"), new XdmAtomicValue(3));

            // Evaluate the XPath expression
            Console.WriteLine(selector.EvaluateSingle().ToString());
        }
Example #7
0
        /// <summary>
        /// Execute an XPath expression containing undeclared variables
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Create the XPath expression.
            XPathCompiler compiler = processor.NewXPathCompiler();
            compiler.AllowUndeclaredVariables = true;
            XPathExecutable expression = compiler.Compile("$a + $b");
            XPathSelector selector = expression.Load();

            // Set the values of the variables
            IEnumerator vars = expression.EnumerateExternalVariables();
            while (vars.MoveNext())
            {
                selector.SetVariable((QName)vars.Current, new XdmAtomicValue(10));
            }

            // Evaluate the XPath expression
            Console.WriteLine(selector.EvaluateSingle().ToString());
        }
Example #8
0
        /// <summary>
        /// Run a transformation: simplest possible script
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));

            // Create an XPath compiler
            XPathCompiler xpath = processor.NewXPathCompiler();

            // Enable caching, so each expression is only compiled once
            xpath.Caching = true;

            // Compile and evaluate some XPath expressions
            foreach (XdmItem item in xpath.Evaluate("//ITEM", input))
            {
                Console.WriteLine("TITLE: " + xpath.EvaluateSingle("string(TITLE)", item));
                Console.WriteLine("PRICE: " + xpath.EvaluateSingle("string(PRICE)", item));
            }
        }
Example #9
0
        /// <summary>
        /// Run an XSLT transformation from an Xdm tree, starting at a node that is not the document node
        /// </summary>
        /// <param name="fileNames">
        /// 1. The source document
        /// 2. The stylesheet
        /// </param>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/othello.xml"));

            // Navigate to the first grandchild
            XPathSelector eval = processor.NewXPathCompiler().Compile("/PLAY/FM[1]").Load();
            eval.ContextItem = input;
            input = (XdmNode)eval.EvaluateSingle();

            // Create an XSLT compiler
            XsltCompiler compiler = processor.NewXsltCompiler();

            // Compile the stylesheet
            XsltTransformer transformer = compiler.Compile(new Uri(samplesDir, "styles/summarize.xsl")).Load();

            // Run the transformation
            transformer.InitialContextNode = input;
            XdmDestination result = new XdmDestination();
            transformer.Run(result);

            // Serialize the result so we can see that it worked
            Console.WriteLine(result.XdmNode.OuterXml);
        }
Example #10
0
        /// <summary>
        /// Run a transformation driven by an xml-stylesheet processing instruction in the source document
        /// </summary>
        /// <param name="fileNames">
        /// 1. The source document
        /// </param>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();
            XsltExecutable exec;

            // Load the source document
            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(samplesDir, "data/books.xml"));
            //Console.WriteLine("=============== source document ===============");
            //Console.WriteLine(input.OuterXml);
            //Console.WriteLine("=========== end of source document ============");

            // Navigate to the xml-stylesheet processing instruction having the pseudo-attribute type=text/xsl;
            // then extract the value of the href pseudo-attribute if present

            String path = @"/processing-instruction(xml-stylesheet)[matches(.,'type\s*=\s*[''""]text/xsl[''""]')]" +
                    @"/replace(., '.*?href\s*=\s*[''""](.*?)[''""].*', '$1')";

            XPathSelector eval = processor.NewXPathCompiler().Compile(path).Load();
            eval.ContextItem = input;
            XdmAtomicValue hrefval = (XdmAtomicValue)eval.EvaluateSingle();
            String href = (hrefval == null ? null : hrefval.ToString());

            if (href == null || href == "")
            {
                Console.WriteLine("No suitable xml-stylesheet processing instruction found");
                return;

            }
            else if (href[0] == '#')
            {

                // The stylesheet is embedded in the source document and identified by a URI of the form "#id"

                Console.WriteLine("Locating embedded stylesheet with href = " + href);
                String idpath = "id('" + href.Substring(1) + "')";
                eval = processor.NewXPathCompiler().Compile(idpath).Load();
                eval.ContextItem = input;
                XdmNode node = (XdmNode)eval.EvaluateSingle();
                if (node == null)
                {
                    Console.WriteLine("No element found with ID " + href.Substring(1));
                    return;
                }
                exec = processor.NewXsltCompiler().Compile(node);

            }
            else
            {

                // The stylesheet is in an external document

                Console.WriteLine("Locating stylesheet at uri = " + new Uri(input.BaseUri, href));

                // Fetch and compile the referenced stylesheet
                exec = processor.NewXsltCompiler().Compile(new Uri(input.BaseUri, href.ToString()));
            }

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

            // Run it
            transformer.InitialContextNode = input;
            XdmDestination results = new XdmDestination();
            transformer.Run(results);
            Console.WriteLine("1: " + results.XdmNode.OuterXml);
        }
Example #11
0
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor(true);


            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();

            processor.SchemaManager.Compile(new Uri(samplesDir, "data/books.xsd"));

            // add a reader
            XmlReader xmlReader = XmlReader.Create(UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));

            DocumentBuilder builder = processor.NewDocumentBuilder();

            builder.SchemaValidationMode = SchemaValidationMode.Strict;
            XdmNode doc = builder.Build(xmlReader);

            XPathCompiler compiler = processor.NewXPathCompiler();
            compiler.ImportSchemaNamespace("");
            XPathExecutable exp = compiler.Compile("if (//ITEM[@CAT='MMP']/QUANTITY instance of element(*,xs:integer)*) then 'true' else 'false'");
            XPathSelector eval = exp.Load();
            eval.ContextItem = doc;
            XdmAtomicValue result = (XdmAtomicValue)eval.EvaluateSingle();
            Console.WriteLine("Result type: " + result.ToString());
        }