Example #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();
        }
Example #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();
        }
Example #3
0
 public Xsl2Processor()
 {
     // Create a Processor instance.
     _processor = new Processor();
     _compiler = _processor.NewXsltCompiler();
     
 }
Example #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();
        }
        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();
        }
        public static string ImportSchematron(string baseDir, string schemaPath, string xsltPath)
        {
            // Builds a new XSLT file from a schematron file.
            // This only needs to be done when the schematron file changes.
            var sxnProc = new Processor();

            var outPath = xsltPath;
            var baseXsltPath = Path.Combine(baseDir, @"Content\Saxon\");

            var schConverter = new string[]
                                   {
                                       baseXsltPath + "iso_dsdl_include.xsl",
                                       baseXsltPath + "iso_abstract_expand.xsl",
                                       baseXsltPath + "iso_svrl_for_xslt2.xsl"
                                   };
            var schemaUri = new Uri(schemaPath);
            var xslComp = sxnProc.NewXsltCompiler();

            //////transform-1/////
            var xslUri = new Uri(schConverter[0]);
            var xslExec = xslComp.Compile(xslUri);
            var xslTrans = xslExec.Load();
            var domOut1 = new DomDestination(new XmlDocument());
            using(var fs = File.Open(schemaPath, FileMode.Open, FileAccess.Read))
            {
                xslTrans.SetInputStream(fs, schemaUri); // set baseUri
                xslTrans.Run(domOut1);
            }

            //////transform-2/////
            xslUri = new Uri(schConverter[1]);
            xslExec = xslComp.Compile(xslUri);
            xslTrans = xslExec.Load();
            var domOut2 = new DomDestination(new XmlDocument());
            var docBuilder = sxnProc.NewDocumentBuilder();
            docBuilder.BaseUri = schemaUri;
            var inputDoc2 = docBuilder.Wrap(domOut1.XmlDocument);
            xslTrans.InitialContextNode = inputDoc2;
            xslTrans.Run(domOut2);

            //////transform-3/////
            xslUri = new Uri(schConverter[2]);
            xslExec = xslComp.Compile(xslUri);
            xslTrans = xslExec.Load();
            var inputDoc3 = docBuilder.Wrap(domOut2.XmlDocument);
            xslTrans.InitialContextNode = inputDoc3;
            var serializer = new Serializer();
            using (TextWriter tw = new StreamWriter(outPath, false))
            {
                serializer.SetOutputWriter(tw);
                serializer.SetOutputProperty(Serializer.INDENT, "no");
                xslTrans.Run(serializer);
            }

            return outPath;
        }
        public SaxonDotNetTransform(string sTransformName, string sTargetLanguageCode)
            : base(sTargetLanguageCode)
        {
            // Create a Processor instance.
            m_processor = new Processor();
            m_compiler = m_processor.NewXsltCompiler();

            // Load transform from file
            var uri = new Uri(sTransformName);
            var errorList = new List<StaticError>();
            m_compiler.ErrorList = errorList;
            var t = m_compiler.Compile(uri);
            m_transformer = t.Load();
        }
Example #8
0
        private void Init (HttpContext context) {
            AppSettings baseXslt = new AppSettings();
            String xsltUri = context.Server.MapPath(baseXslt.GetSetting("baseTemplate"));
            Uri xUri = new Uri(xsltUri);

            this._Resolver = new XmlUrlResolver();
            this._Resolver.Credentials = CredentialCache.DefaultCredentials;

            this._TemplateStream = (Stream)this._Resolver.GetEntity(xUri, null, typeof(Stream));
            this._Processor = new Processor();
            this._Compiler = _Processor.NewXsltCompiler();
            this._Compiler.BaseUri = xUri;
            this._Template = this._Compiler.Compile(_TemplateStream);
            this._IS_INITIALIZED = true;
        }
Example #9
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();
        }
Example #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();
        }
Example #11
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;
        }
Example #12
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");
        }
Example #13
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;
        }
 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;
 }
Example #16
0
        /// <summary>
        /// Run an XSLT transformation using the id() function, with DTD validation
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance
            Processor processor = new Processor();

            // Load the source document. The Microsoft .NET parser does not report attributes of type ID. The only
            // way to use the function is therefore (a) to use a different parser, or (b) to use xml:id instead. We
            // choose the latter course.

            String doc = "<!DOCTYPE table [" +
                "<!ELEMENT table (row*)>" +
                "<!ELEMENT row EMPTY>" +
                "<!ATTLIST row xml:id ID #REQUIRED>" +
                "<!ATTLIST row value CDATA #REQUIRED>]>" +
                "<table><row xml:id='A123' value='green'/><row xml:id='Z789' value='blue'/></table>";

            DocumentBuilder builder = processor.NewDocumentBuilder();
            builder.DtdValidation = true;
            builder.BaseUri = samplesDir;
            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);

            // Define a stylesheet that uses the id() function
            String stylesheet =
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
                "<xsl:template match='/'>\n" +
                "  <xsl:copy-of select=\"id('Z789')\"/>\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;

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

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

            // Show the result
            Console.WriteLine(results.XdmNode.ToString());
        }
Example #17
0
        /// <summary>
        /// Run an XSLT transformation capturing run-time messages within the application
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Ask for the JAXP parser to be used (or not to be used, if false)
            processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "false");

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

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

            // Define a stylesheet that shows line numbers of source elements
            String stylesheet =
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0' xmlns:saxon='http://saxon.sf.net/'>\n" +
                "<xsl:template match='/'>\n" +
                "<out>\n" +
                "  <xsl:for-each select='//ACT'>\n" +
                "  <out><xsl:value-of select='saxon:line-number(.)'/></out>\n" +
                "  </xsl:for-each>\n" +
                "</out>\n" +
                "</xsl:template>\n" +
                "</xsl:stylesheet>";

            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;

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

            // Transform the source XML to System.out.
            transformer.Run(serializer);
        }
Example #18
0
        public void Transform(Engine engine, Template template, Package package)
        {
            m_Engine = engine;
            m_Package = package;

            m_Logger.Debug(String.Format("XSLT Meditator executing: '{0}' ", template.Id));

            ReadParameters();

            using (MemoryStream templateStream = GetStringAsStream(template.Content))
            {
                var xslt = new XPathDocument(templateStream);// Create an new XmlDocument to hold the XSLT of the current Template Building Block // Load the contents (xslt) of the TBB into the XmlDocument
                var input = new XmlTextReader(new StringReader(m_XmlInput.GetAsString())); //need to use the stringreader for xml in the package marked with encoding=utf-16 otherwise an encoding exception is thrown during the transformation

                //no need to worry about XsltSettings, the default should work for SAXON
                // var xsltSettings = new XsltSettings(); // Create an XsltSettings object to override the default XSLT settings for XslCompiledTransform
                //xsltSettings.EnableDocumentFunction = true; // Enable script and document() funtion (default in .NET is disabled
                //xsltSettings.EnableScript = true;

                var resolver = new TcmUriResolver(engine); //Create a new UriResolver which supports TridionURIs (Only http:// and file:// are supported in the default one)

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

                XsltCompiler compiler = processor.NewXsltCompiler();

                //set resolver
                compiler.XmlResolver = resolver;

                //compile the xslt
                XsltTransformer transformer = compiler.Compile(templateStream).Load();

                //set parameters
                //TODO:  AddExtensionObjects(XsltArgumentList arglist)  Those are a list of extension functions needs to be added
                //

                //  args.AddParam("TEMPLATE_URI", "", m_Engine.PublishingContext.ResolvedItem.Template.Id.ToString()); // Add the URI of the current template as the parameter
                //transformer.SetParameter(new QName("", "", "TEMPLATE_URI"), new XdmAtomicValue(m_Engine.PublishingContext.ResolvedItem.Template.Id.ToString()));

                //set paramters
                SetParameterCollection(transformer);

                transformer.InputXmlResolver = resolver;

                using (var results = new StringWriter()) // Create an XmlWriter which has the same output settings as the transformer
                {
                    using (var xmlwriter = XmlWriter.Create(results))
                    {
                        // 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(new TextWriterDestination(xmlwriter));
                        //serializer.SetOutputProperty(Serializer.INDENT, "yes");

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

                        // Transform the source XML
                        transformer.Run(new TextWriterDestination(xmlwriter));

                        Tridion.ContentManager.Templating.Item xsltOutputItem = package.CreateStringItem(GetContentType(template.Content), results.ToString());

                        if (m_OutputItemName == Package.OutputName)
                        {
                            xsltOutputItem.Properties[OUTPUT_BASE_URI] = template.Id; //mimic the behaviour of the DW mediator when the output item name is "Output"
                        }

                        package.PushItem(m_OutputItemName, xsltOutputItem); // Push the results into the package
                    }
                }
            }
        }
Example #19
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 a transformer for the stylesheet.
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/books.xsl")).Load();

            // 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();
            serializer.SetOutputWriter(Console.Out);

            // Transform the source XML and serialize the result document
            transformer.Run(serializer);
        }
Example #20
0
        /// <summary>
        /// Run the transformation, sending the serialized output to a file
        /// </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 transformer for the stylesheet.
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/identity.xsl")).Load();

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

            // Create a serializer
            String outfile = "OutputFromXsltSimple2.xml";
            Serializer serializer = new Serializer();
            serializer.SetOutputStream(new FileStream(outfile, FileMode.Create, FileAccess.Write));

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

            Console.WriteLine("\nOutput written to " + outfile + "\n");
        }
Example #21
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());
     }
 }
 private XsltExecutable getXhtmlCanonizer(Processor p) {
     if (xhtmlCanonizer == null) {
         xhtmlCanonizer = p.NewXsltCompiler().Compile(
             new FileStream(testSuiteDir + "SaxonResults/canonizeXhtml.xsl", FileMode.Open));
     }
     return xhtmlCanonizer;
 }
Example #23
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 #24
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.
        }
Example #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);
        }
Example #26
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);
            }
        }
Example #27
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());
        }
Example #28
0
        /// <summary>
        /// Run a transformation: supply input as a file
        /// </summary>
        public override void run(Uri samplesDir)
        {
            if (samplesDir.Scheme != Uri.UriSchemeFile)
            {
                Console.WriteLine("Supplied URI must be a file directory");
            }
            String dir = samplesDir.AbsolutePath;
            String sourceFile = dir + "data/books.xml";
            String styleFile = dir + "styles/books.xsl";

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

            // Load the source document

            DocumentBuilder builder = processor.NewDocumentBuilder();
            builder.BaseUri = new Uri(samplesDir, "data/books.xml");

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

            // Create a transformer for the stylesheet.
            XsltCompiler compiler = processor.NewXsltCompiler();
            compiler.BaseUri = new Uri(samplesDir, "styles/books.xsl");
            XsltTransformer transformer = compiler.Compile(File.OpenRead(styleFile)).Load();

            // 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();
            serializer.SetOutputWriter(Console.Out);

            // Transform the source XML and serialize the result document
            transformer.Run(serializer);
        }
Example #29
0
        /// <summary>
        /// Run a transformation: simplest possible script
        /// </summary>
        public override void run(Uri samplesDir)
        {
            Processor processor = new Processor();

            // Load the source document
            DocumentBuilder builder = processor.NewDocumentBuilder();
            builder.BaseUri = samplesDir;

            String doc = "<doc>  <a>  <b>text</b>  </a>  <a/>  </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:strip-space elements='*'/>" +
                "<xsl:template match='/'>" +
                "  <xsl:copy-of select='.'/>" +
                "</xsl:template>" +
                "</xsl:stylesheet>";

            XsltCompiler compiler = processor.NewXsltCompiler();
            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;

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

            // Transform the source XML to System.out.
            transformer.Run(serializer);
        }
Example #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;
 }