Ejemplo n.º 1
8
        public static void Transform(Uri StyleSheet, String Input,Encoding Encoding,out String Output)
        {
            Processor processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(new XmlTextReader(new StringReader(Input)));

            processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true");

            XsltCompiler compiler = processor.NewXsltCompiler();

            XsltExecutable executable = compiler.Compile(StyleSheet);

            XsltTransformer transformer = executable.Load();

            transformer.InitialContextNode = input;

            Serializer serializer = new Serializer();

            MemoryStream stream = new MemoryStream();

            System.IO.StreamWriter writer = new StreamWriter(stream);

            serializer.SetOutputWriter(writer);

            transformer.Run(serializer);

            Output = Encoding.GetString(stream.ToArray());

            writer.Close();

            stream.Close();
        }
Ejemplo n.º 2
1
        static void Main(string[] args)
        {
            String s1 = @"<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:output method='xml' indent='yes'/><xsl:template match='/'>";
            String s2 = "This is running an XSLT engine by <xsl:value-of select=\"system-property('xsl:vendor')\" />  <a href=\"{system-property('xsl:vendor-url')}\"><xsl:value-of select=\"system-property('xsl:vendor-url')\" /></a> implementing XSLT v<xsl:value-of select=\"system-property('xsl:version')\" /> ";
            String s3 = @"\n<xsl:apply-templates/></xsl:template><xsl:template match='@*|node()'> ";
            String s4 = @"<xsl:copy><xsl:apply-templates select='@*|node()'/></xsl:copy></xsl:template></xsl:stylesheet>";

            String str = s1 + s2 + s3  + s4;

            //Run Saxon
            //new SaxonTransform().doTransform(args, "Transform");

            //Run Saxon s9 api
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document.
            XdmNode input = processor.NewDocumentBuilder().Build(XmlReader.Create(new StringReader(str)));

            XsltCompiler compiler = processor.NewXsltCompiler();
            //although it is not required in this example, we need to set otherwise exception will be thrown
            compiler.BaseUri = new Uri("http://dummyurl.com");
            // Create a transformer for the stylesheet.
            XsltTransformer transformer = compiler.Compile(XmlReader.Create(new StringReader(str))).Load();

            // BaseOutputUri is only necessary for xsl:result-document.
            //transformer.BaseOutputUri = new Uri("http://dummyurl.com");
            // Set the root node of the source document to be the initial context node.
            transformer.InitialContextNode = input;

            transformer.SetParameter(new QName("", "", "maxmin"), new XdmAtomicValue("parm1"));
            transformer.SetParameter(new QName("", "", "pricestock"), new XdmAtomicValue("parm2"));

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

            // Set the root node of the source document to be the initial context node
            //transformer.InitialTemplate = new QName("","","go");

            serializer.SetOutputWriter(Console.Out);
            serializer.SetOutputProperty(Serializer.INDENT, "yes");

            // serializer.SetOutputFile(Server.MapPath("test.html")); //for file

            // Transform the source XML to System.out.
            transformer.Run(serializer);

            //Call the SaxonMediator
            SaxonMediator mediator = new SaxonMediator();

            //mediator.Transform(null, Template template, Package package)

            //wait for user to exit
            Console.ReadLine();
        }
Ejemplo n.º 3
0
    public void GenXML()
    {
        String sourceUri = Server.MapPath("5648.xml");
        String xqUri = Server.MapPath("graph.xq");

        using (FileStream sXml = File.OpenRead(sourceUri))
        {
            using (FileStream sXq = File.OpenRead(xqUri))
            {
                Processor processor = new Processor();
                XQueryCompiler compiler = processor.NewXQueryCompiler();
                compiler.BaseUri = sourceUri;
                XQueryExecutable exp = compiler.Compile(sXq);
                XQueryEvaluator eval = exp.Load();

                DocumentBuilder loader = processor.NewDocumentBuilder();
                loader.BaseUri = new Uri(sourceUri);
                XdmNode indoc = loader.Build(new FileStream(sourceUri, FileMode.Open, FileAccess.Read));

                eval.ContextItem = indoc;
                Serializer qout = new Serializer();
                qout.SetOutputProperty(Serializer.METHOD, "xml");
                qout.SetOutputProperty(Serializer.INDENT, "yes");
                qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
                qout.SetOutputWriter(Response.Output);
                eval.Run(qout);
            }
        }
    }
Ejemplo n.º 4
0
        public static void Transform(String StylesheetFilename, String SourceFilename, String OutputFilename)
        {
            if (StylesheetFilename.StartsWith(".\\"))
            {
                StylesheetFilename = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + StylesheetFilename;
            }

            Processor processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(new Uri(SourceFilename));

            processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true");

            XsltCompiler compiler = processor.NewXsltCompiler();

            XsltExecutable executable = compiler.Compile(new Uri(StylesheetFilename));

            XsltTransformer transformer = executable.Load();

            transformer.InitialContextNode = input;

            Serializer serializer = new Serializer();

            System.IO.StreamWriter stream = new StreamWriter(OutputFilename);

            serializer.SetOutputWriter(stream);

            transformer.Run(serializer);

            stream.Close();
        }
Ejemplo n.º 5
0
        public string Transform(string baseDir, string sourceXml, string releaseType, string version)
        {
            var sourceXsl = SchematronBuilder.CheckForNewerSchematron(baseDir, releaseType, version);

            // Create a Processor instance.
            var processor = new Processor();

            var result = new StringBuilder();

            var xmlDocumentBuilder = processor.NewDocumentBuilder();
            xmlDocumentBuilder.BaseUri = new Uri(baseDir);

            var xsltCompiler = processor.NewXsltCompiler();
            xsltCompiler.ErrorList = new ArrayList();
            var xmlToValidate = xmlDocumentBuilder.Build(new StringReader(sourceXml));
            var compiledXsl = xsltCompiler.Compile(new XmlTextReader(sourceXsl));
            var xmlValidator = compiledXsl.Load();

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

            // BaseOutputUri is only necessary for xsl:result-document.
            xmlValidator.BaseOutputUri = new Uri(Path.Combine(baseDir, "output.xml"));

            var validationSerializer = new Serializer();

            using (var resultsWriter = new StringWriter(result))
            {
                validationSerializer.SetOutputWriter(resultsWriter);
                xmlValidator.Run(validationSerializer);
            }

            return result.ToString();
        }
Ejemplo n.º 6
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);
 }
Ejemplo n.º 7
0
        internal XmlDocument DoTransform()
        {
            Processor processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Wrap(_docToTransform);

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

            DocumentBuilder builder = processor.NewDocumentBuilder();
            XdmNode xsltSheetNode = builder.Build(_xsltDocReader);

            // Compile the stylesheet
            XsltTransformer transformer = compiler.Compile(xsltSheetNode).Load();

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

            return result.XmlDocument;
        }
Ejemplo n.º 8
0
        private string xml2HtmlTree()
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(this.Xsd);
            StreamReader xsl = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Areas/MSM/Resources/Stylesheets/xsd2htmlTree.xslt");

            Processor processor = new Processor();
            XdmNode input = processor.NewDocumentBuilder().Build(xml);
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(xsl).Load();
            transformer.InitialContextNode = input;
            StringWriter writer = new StringWriter();
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(writer);
            transformer.Run(serializer);
            return writer.ToString();
        }
Ejemplo n.º 9
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();
        }
Ejemplo n.º 10
0
        public static void Main()
        {
            using (FileStream streamXml = File.OpenRead(XmlPath))
            {
                using (FileStream streamXsl = File.OpenRead(XsltPath))
                {
                    Processor processor = new Processor();

                    DocumentBuilder builder = processor.NewDocumentBuilder();
                    Uri uri = new Uri("urn:catalogue");
                    builder.BaseUri = uri;
                    XdmNode input = builder.Build(streamXml);
                    XsltTransformer transformer = processor.NewXsltCompiler().Compile(streamXsl).Load();
                    transformer.InitialContextNode = input;
                    Serializer serializer = new Serializer();
                    serializer.SetOutputFile(HtmlPath);
                    transformer.Run(serializer);
                }
            }

            Console.WriteLine("catalogue.html created successfully");
        }
Ejemplo n.º 11
0
        private static XdmNode getXdmNode(String uri, String path) {
            try {

                SgmlReader sr = new SgmlReader();
                sr.Href = uri;

                XmlDocument htmlDoc = new XmlDocument();

                try {
                    htmlDoc.Load(sr);
                } catch (Exception e) {
                    throw;
                }

                XmlNode html = htmlDoc.SelectSingleNode(path);
                Processor processor = new Processor();
                return processor.NewDocumentBuilder().Build(html);

            } catch (Exception e) {
                throw;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SaxonXsltTransform"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="stylesheetMarkup">The stylesheet markup.</param>
        /// <exception cref="SageHelpException"></exception>
        public SaxonXsltTransform(SageContext context, XmlDocument stylesheetMarkup)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(stylesheetMarkup != null);

            UrlResolver resolver = new UrlResolver(context);

            processor = new Processor();

            XdmNode input = processor.NewDocumentBuilder().Build(stylesheetMarkup);
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(XmlReader.Create(stylesheetMarkup.OuterXml)).Load();

            try
            {
                //this.processor.Load(stylesheetMarkup, XsltSettings.TrustedXslt, resolver);
                dependencies.AddRange(resolver.Dependencies);
            }
            catch //(Exception ex)
            {
                //ProblemInfo problem = this.DetectProblemType(ex);
                //throw new SageHelpException(problem, ex);
            }
        }
        private static SVGImage.SVG.SVGImage _convert(XmlReader xml)
        {
            var processor = new Processor();

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

            // Create a transformer for the stylesheet
            if (transformer == null)
            {
                var file = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "libs\\pMML2SVG\\pmml2svg.xsl");
                var xslt = XmlReader.Create(file);
                transformer = processor.NewXsltCompiler().Compile(xslt).Load();
            }

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

            var ms = new MemoryStream();

            // Create a serializer
            var serializer = new Serializer();
            serializer.SetOutputStream(ms);

            // Transform the source XML
            transformer.Run(serializer);

            serializer.Close();

            ms.Position = 0;

            var img = new SVGImage.SVG.SVGImage();
            img.SetImage(ms);
            
            return img;
        }
Ejemplo n.º 14
0
 public XsltTransformationManager
   (
     Processor processor,
     Transform transform,
     XmlUrlResolver resolver,
     Serializer serializer,
     Dictionary<string, XsltTransformer> xsltHashtable,
     Hashtable xmlSourceHashtable,
     Hashtable xdmNodeHashtable,
     Hashtable namedXsltHashtable,
     Hashtable namedXsltETagIndex,
     Hashtable xdmNodeETagIndex,
     Uri baseXsltUri,
     String baseXsltUriHash,
     String baseXsltName
   ) {
     m_baseXsltUri = baseXsltUri;
     m_baseXsltUriHash = baseXsltUriHash;
     m_baseXsltName = baseXsltName;
     m_transform = transform;
     m_xsltHashtable = xsltHashtable;
     m_processor = processor;
     m_compiler = m_processor.NewXsltCompiler();
     m_sourceHashtable = xmlSourceHashtable;
     m_resolver = resolver;
     m_compiler.XmlResolver = m_resolver;
     m_builder = m_processor.NewDocumentBuilder();
     m_serializer = serializer;
     m_xdmNodeHashtable = xdmNodeHashtable;
     m_xdmNodeETagIndex = xdmNodeETagIndex;
     m_namedXsltHashtable = namedXsltHashtable;
     m_namedXsltETagIndex = namedXsltETagIndex;
     _hashAlgorithm = HashAlgorithm.MD5;
     //NOTE: TransformEngine enum PLACEHOLDER FOR FUTURE USE
     m_transformEngine = TransformEngine.SAXON;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Show a transformation using a registered collection
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

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

            // Define a stylesheet that splits the document up
            String stylesheet =
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
                "<xsl:template name='main'>\n" +
                " <out>\n" +
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
                "  </xsl:for-each><zzz/>\n" +
                "  <xsl:for-each select=\"collection('http://www.example.org/my-collection')\">\n" +
                "    <document uri='{document-uri(.)}' nodes='{count(//*)}'/>\n" +
                "  </xsl:for-each>\n" +
                " </out>\n" +
                "</xsl:template>\n" +
                "</xsl:stylesheet>";

            Uri[] documentList = new Uri[2];
            documentList[0] = new Uri(samplesDir, "data/othello.xml");
            documentList[1] = new Uri(samplesDir, "data/books.xml");
            processor.RegisterCollection(new Uri("http://www.example.org/my-collection"), documentList);

            XsltCompiler compiler = processor.NewXsltCompiler();
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));

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

            // Set the root node of the source document to be the initial context node
            transformer.InitialTemplate = new QName("", "main");

            //Set the destination
            XdmDestination results = new XdmDestination();

            // Transform the XML
            transformer.Run(results);

            // Show the result
            Console.WriteLine(results.XdmNode.ToString());
        }
    /**
    * 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.");
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Show a transformation using a user-written result document handler. This example
        /// captures each of the result documents in a DOM, and creates a Hashtable that indexes
        /// the DOM trees according to their absolute URI. On completion, it writes all the DOMs
        /// to the standard output.
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

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

            // Define a stylesheet that splits the document up
            String stylesheet =
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
                "<xsl:template match='/'>\n" +
                "  <xsl:for-each select='//ACT'>\n" +
                "    <xsl:result-document href='{position()}.xml'>\n" +
                "      <xsl:copy-of select='TITLE'/>\n" +
                "    </xsl:result-document>\n" +
                "  </xsl:for-each>\n" +
                "</xsl:template>\n" +
                "</xsl:stylesheet>";

            XsltCompiler compiler = processor.NewXsltCompiler();
            compiler.BaseUri = new Uri("http://localhost/stylesheet");
            XsltExecutable exec = compiler.Compile(new StringReader(stylesheet));

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

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

            // Establish the result document handler
            Hashtable results = new Hashtable();
            transformer.ResultDocumentHandler = new UserResultDocumentHandler(results);

            // Transform the source XML to a NullDestination (because we only want the secondary result files).
            transformer.Run(new NullDestination());

            // Process the captured DOM results
            foreach (DictionaryEntry entry in results)
            {
                string uri = (string)entry.Key;
                Console.WriteLine("\nResult File " + uri);
                DomDestination dom = (DomDestination)results[uri];
                Console.Write(dom.XmlDocument.OuterXml);
            }
        }
Ejemplo n.º 18
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)");
        }
Ejemplo n.º 19
0
 private void generateButton_Click(object sender, System.EventArgs e)
 {
     try
     {
         generateButton.Enabled = false;
         Cursor.Current = Cursors.WaitCursor;
         Processor processor = new Processor();
         DocumentBuilder builder = processor.NewDocumentBuilder();
         builder.BaseUri = new Uri(xmlSource.Text);
         XdmNode input = builder.Build(new FileStream(xmlSource.Text, FileMode.Open));
         XsltCompiler compiler = processor.NewXsltCompiler();
         compiler.BaseUri = new Uri(htmlDest.Text);
         XsltTransformer transformer = compiler.Compile(xsltStream).Load();
         transformer.InitialContextNode = input;
         Serializer serializer = new Serializer();
         serializer.SetOutputStream(new FileStream(htmlDest.Text, FileMode.Create, FileAccess.Write));
         transformer.Run(serializer);
         Cursor.Current = Cursors.Default;
         generateButton.Enabled = true;
     }
     catch (Exception ex)
     {
         Cursor.Current = Cursors.Default;
         generateButton.Enabled = true;
         MessageBox.Show(ex.ToString());
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Transform from an XDM tree to an XDM tree
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

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

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

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

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

            // Serialize the result so we can see that it worked
            StringWriter sw = new StringWriter();
            result.XdmNode.WriteTo(new XmlTextWriter(sw));
            Console.WriteLine(sw.ToString());

            // Note: we don't do
            //   result.XdmNode.WriteTo(new XmlTextWriter(Console.Out));
            // because that results in the Console.out stream being closed,
            // with subsequent attempts to write to it being rejected.
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Show a query producing a sequence as its result and returning the sequence
        /// to the C# application in the form of an iterator. The sequence is then
        /// output by serializing each item individually, with each item on a new line.
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();
            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
            //XmlTextReader reader = new XmlTextReader(inputFileName,
            //    new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
            XmlTextReader reader = new XmlTextReader(inputFileName,
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
            reader.Normalization = true;

            // add a validating reader - not to perform validation, but to expand entity references
            XmlValidatingReader validator = new XmlValidatingReader(reader);
            validator.ValidationType = ValidationType.None;

            XdmNode doc = processor.NewDocumentBuilder().Build(reader);

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            XQueryExecutable exp = compiler.Compile("//ISBN");
            XQueryEvaluator eval = exp.Load();
            eval.ContextItem = doc;

            foreach (XdmNode node in eval)
            {
                Console.WriteLine(node.OuterXml);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Show a query producing a Saxon tree as its input and producing a Saxon tree as its output
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();

            DocumentBuilder loader = processor.NewDocumentBuilder();
            loader.BaseUri = new Uri(samplesDir, "data/books.xml");
            XdmNode indoc = loader.Build(loader.BaseUri);

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
            XQueryEvaluator eval = exp.Load();
            eval.ContextItem = indoc;
            XdmDestination qout = new XdmDestination();
            eval.Run(qout);
            XdmNode outdoc = qout.XdmNode;
            Console.WriteLine(outdoc.OuterXml);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Show a query producing a DOM as its input and producing a DOM as its output
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();

            XmlDocument input = new XmlDocument();
            input.Load(new Uri(samplesDir, "data/books.xml").ToString());
            XdmNode indoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(input));

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            XQueryExecutable exp = compiler.Compile("<doc>{reverse(/*/*)}</doc>");
            XQueryEvaluator eval = exp.Load();
            eval.ContextItem = indoc;
            DomDestination qout = new DomDestination();
            eval.Run(qout);
            XmlDocument outdoc = qout.XmlDocument;
            Console.WriteLine(outdoc.OuterXml);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Show a query reading an input document using an XmlReader (the .NET XML parser)
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();

            String inputFileName = new Uri(samplesDir, "data/books.xml").ToString();
            XmlTextReader reader = new XmlTextReader(inputFileName,
                UriConnection.getReadableUriStream(new Uri(samplesDir, "data/books.xml")));
            //new FileStream(inputFileName, FileMode.Open, FileAccess.Read));
            reader.Normalization = true;

            // add a validating reader - not to perform validation, but to expand entity references
            XmlValidatingReader validator = new XmlValidatingReader(reader);
            validator.ValidationType = ValidationType.None;

            XdmNode doc = processor.NewDocumentBuilder().Build(validator);

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            XQueryExecutable exp = compiler.Compile("/");
            XQueryEvaluator eval = exp.Load();
            eval.ContextItem = doc;
            Serializer qout = new Serializer();
            qout.SetOutputProperty(Serializer.METHOD, "xml");
            qout.SetOutputProperty(Serializer.INDENT, "yes");
            qout.SetOutputStream(new FileStream("testoutput2.xml", FileMode.Create, FileAccess.Write));
            eval.Run(qout);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Run an XSLT transformation making use of an XmlResolver to resolve URIs both at compile time and at run-time
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Load the source document
            DocumentBuilder builder = processor.NewDocumentBuilder();
            UserXmlResolver buildTimeResolver = new UserXmlResolver();
            buildTimeResolver.Message = "** Calling build-time XmlResolver: ";
            builder.XmlResolver = buildTimeResolver;
            builder.BaseUri = samplesDir;

            String doc = "<!DOCTYPE doc [<!ENTITY e SYSTEM 'flamingo.txt'>]><doc>&e;</doc>";
            MemoryStream ms = new MemoryStream();
            StreamWriter tw = new StreamWriter(ms);
            tw.Write(doc);
            tw.Flush();
            Stream instr = new MemoryStream(ms.GetBuffer(), 0, (int)ms.Length);
            XdmNode input = builder.Build(instr);

            // Create a transformer for the stylesheet.
            String stylesheet =
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>" +
                "<xsl:import href='empty.xslt'/>" +
                "<xsl:template match='/'>" +
                "<out note=\"{doc('heron.txt')}\" ><xsl:copy-of select='.'/></out>" +
                "</xsl:template>" +
                "</xsl:stylesheet>";

            XsltCompiler compiler = processor.NewXsltCompiler();
            UserXmlResolver compileTimeResolver = new UserXmlResolver();
            compileTimeResolver.Message = "** Calling compile-time XmlResolver: ";
            compiler.XmlResolver = compileTimeResolver;
            compiler.BaseUri = samplesDir;
            XsltTransformer transformer = compiler.Compile(new XmlTextReader(new StringReader(stylesheet))).Load();

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

            // Set the user-written XmlResolver
            UserXmlResolver runTimeResolver = new UserXmlResolver();
            runTimeResolver.Message = "** Calling transformation-time XmlResolver: ";
            transformer.InputXmlResolver = runTimeResolver;

            // Create a serializer
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(Console.Out);

            // Transform the source XML to System.out.
            transformer.Run(serializer);
        }
Ejemplo n.º 26
0
            /**
             * 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 String canonizeXhtml(Processor p, String input) {
     try {
         XsltExecutable canonizer = getXhtmlCanonizer(p);
         XsltTransformer t = canonizer.Load();
         StringWriter sw = new StringWriter();
         Serializer r = new Serializer();
         r.SetOutputWriter(sw);
         t.InitialContextNode = p.NewDocumentBuilder().Build(
             new FileStream(input, FileMode.Open));
         t.Run(r);
         return sw.ToString();
     } catch (Exception err) {
         Console.WriteLine("*** Failed to compile or run XHTML canonicalizer stylesheet: " + err.ToString());
     }
     return "";
 }
Ejemplo n.º 28
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));
            }
        }
Ejemplo n.º 29
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);
        }
Ejemplo n.º 30
-22
 private static XmlDocument Process (XmlReader funcSeq, XmlReader extTransform, Uri baseUri) {
   Processor processor = new Processor();
   XdmNode input = processor.NewDocumentBuilder().Build(funcSeq);
   XsltCompiler compiler = processor.NewXsltCompiler();
   compiler.BaseUri = baseUri;
   XsltTransformer transformer = compiler.Compile(extTransform).Load();
   transformer.InitialContextNode = input;
   DomDestination result = new DomDestination();
   transformer.Run(result);
   return result.XmlDocument;
 }