Exemplo 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();
        }
Exemplo 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();
        }
Exemplo n.º 3
0
        public override void TransformFileToFile(XMLUtilities.XSLParameter[] parameterList, string sInputPath, string sOutputName)
        {
            try
            {

                // Add any parameters
                AddParameters(parameterList);

                // apply transform
                var inputUri = new Uri(sInputPath);
                var sr = new StreamReader(sInputPath, Encoding.UTF8);
                XdmNode inputNode = m_processor.NewDocumentBuilder().Build(inputUri);
                sr.Close();
                m_transformer.InitialContextNode = inputNode;

                var ser = new Serializer();
                ser.SetOutputFile(sOutputName);

                m_transformer.Run(ser);
                ser.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.InnerException.ToString());
            }
        }
Exemplo n.º 4
0
        public void Process (HttpContext context, TextWriter writer) {

            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            String sourceUri = context.Server.MapPath(Request.RawUrl);
            Uri sUri = new Uri(sourceUri);

            if (!this._IS_INITIALIZED) Init(context);

            using (Stream sXml = (Stream)this._Resolver.GetEntity(sUri, null, typeof(Stream))) {

                using (_TemplateStream) {

                    DocumentBuilder builder = _Processor.NewDocumentBuilder();
                    builder.BaseUri = sUri;
                    XdmNode input = builder.Build(sXml);

                    Serializer mySerializer = new Serializer();
                    mySerializer.SetOutputWriter(writer);

                    XsltTransformer myTransformer = this._Template.Load();
                    myTransformer.InputXmlResolver = this._Resolver;
                    myTransformer.InitialContextNode = input;
                    myTransformer.Run(mySerializer);
                }
            }

        }
Exemplo n.º 5
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();
        }
Exemplo n.º 6
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();
        }
Exemplo n.º 7
0
    public void ProcessRequest(HttpContext context) {

      _requestMethod = context.Request.HttpMethod;
      _writer = context.Response.Output;
      _context = context;
      _processor = (Processor)context.Application["processor"];
      _compiler = (XsltCompiler)context.Application["compiler"];
      _serializer = (Serializer)context.Application["serializer"];
      _resolver = (XmlUrlResolver)context.Application["resolver"];
      _globalXsltParams = (Hashtable)context.Application["globalXsltParams"];
      _sessionXsltParams = (Hashtable)context.Application["sessionXsltParams"];
      _requestXsltParams = (Hashtable)context.Application["requestXsltParams"];
      Hashtable xsltParams = new Hashtable();
      foreach (DictionaryEntry param in _globalXsltParams) {
        xsltParams[param.Key] = param.Value;
      }
      foreach (DictionaryEntry param in _sessionXsltParams) {
        xsltParams[param.Key] = param.Value;
      }
      foreach (DictionaryEntry param in _requestXsltParams) {
        xsltParams[param.Key] = param.Value;
      }
      _transformContext = new Context(context, _processor, _compiler, _serializer, _resolver, xsltParams);

      switch (_requestMethod) {

        case "GET": {
            new Transform().Process(_transformContext);
            break;
          }
        case "PUT": {
            new Transform().Process(_transformContext);
            break;
          }
        case "POST": {
            new Transform().Process(_transformContext);
            break;
          }
        case "DELETE": {
            new Transform().Process(_transformContext);
            break;
          }
        default: {
            new Transform().Process(_transformContext);
            break;
          }
      }
    }
Exemplo 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();
        }
Exemplo n.º 9
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");
        }
Exemplo n.º 10
0
 public XsltTransformationManager
   (
     Processor processor,
     Transform transform,
     XmlUrlResolver resolver,
     Serializer serializer,
     Hashtable xsltHashtable,
     Hashtable xmlSourceHashtable,
     Hashtable xdmNodeHashtable,
     Hashtable namedXsltHashtable,
     Hashtable namedXsltETagIndex,
     Hashtable xdmNodeETagIndex,
     Uri baseXsltUri,
     String baseXsltUriHash,
     String baseXsltName
   )
 {
     _baseXsltUri = baseXsltUri;
     _baseXsltUriHash = baseXsltUriHash;
     _baseXsltName = baseXsltName;
     _transform = transform;
     _xsltHashtable = xsltHashtable;
     _processor = processor;
     _compiler = _processor.NewXsltCompiler();
     _sourceHashtable = xmlSourceHashtable;
     _resolver = resolver;
     _compiler.XmlResolver = _resolver;
     _builder = _processor.NewDocumentBuilder();
     _serializer = serializer;
     _xdmNodeHashtable = xdmNodeHashtable;
     _xdmNodeETagIndex = xdmNodeETagIndex;
     _namedXsltHashtable = namedXsltHashtable;
     _namedXsltETagIndex = namedXsltETagIndex;
     _hashAlgorithm = HashAlgorithm.SHA1;
     //NOTE: TransformEngine enum PLACEHOLDER FOR FUTURE USE
     _transformEngine = TransformEngine.SAXON;
 }
Exemplo n.º 11
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;
     m_hashAlgorithm = HashAlgorithm.MD5;
     //NOTE: TransformEngine enum PLACEHOLDER FOR FUTURE USE
     m_transformEngine = TransformEngine.SAXON;
 }
        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 XmlDestination HandleResultDocument(string href, Uri baseUri)
 {
     var dest = new Serializer();
     dest.SetOutputFile(Path.Combine(baseUri.LocalPath, href));
     return dest;
 }
Exemplo n.º 14
0
        protected void Application_Start(object sender, EventArgs e)
        {
            //System.Web.HttpApplication application = (System.Web.HttpApplication)sender;

            m_useMemCached = false;
            m_DEBUG = false;
            m_memcachedClient = null;
            m_appSettings = new AppSettings();
            m_xameleonConfiguration = AspNetXameleonConfiguration.GetConfig();
            string hashkey = (string)m_xameleonConfiguration.ObjectHashKey;
            Application["hashkey"] = hashkey;
            m_awsConfiguration = AspNetAwsConfiguration.GetConfig();
            m_transform = new Transform.Transform();
            m_processor = new Processor();
            m_serializer = new Serializer();
            m_resolver = new XmlUrlResolver();
            m_namedXsltHashtable = new Hashtable();
            m_globalXsltParams = new Hashtable();
            m_transformContextHashtable = new Hashtable();
            m_xmlServiceOperationManager = new XPathServiceOperationManager(new Dictionary<int, XPathNavigator>());
            m_geoIPLookup = new Dictionary<String, IPLocation>();
            m_requestXsltParams = null;
            m_encoding = new UTF8Encoding();
            m_pledgeCount = new PledgeCount(0, 0);
            m_pledgeQueue = new Queue<string>();

            string sdbAccessKey = String.Empty;
            string sdbSecretKey = String.Empty;
            string awsUriEndpoint = "https://sdb.amazonaws.com/";

            Environment.SetEnvironmentVariable("AWS_URI_ENDPOINT", awsUriEndpoint);
            

            using (XmlReader configReader = XmlReader.Create(HttpContext.Current.Server.MapPath("~/App_Config/aws.config")))
            {
                while (configReader.Read())
                {
                    if (configReader.IsStartElement())
                    {
                        switch (configReader.Name)
                        {
                            case "sdb-access-key":
                                {
                                    sdbAccessKey = configReader.ReadString();
                                    Environment.SetEnvironmentVariable("AWS_PUBLIC_KEY", sdbAccessKey);
                                    Console.WriteLine("SDB_ACCESS_KEY: {0}", sdbAccessKey);
                                    break;
                                }
                            case "sdb-secret-key":
                                {
                                    sdbSecretKey = configReader.ReadString();
                                    Environment.SetEnvironmentVariable("AWS_PRIVATE_KEY", sdbSecretKey);
                                    Console.WriteLine("SDB_PRIVATE_KEY: {0}", sdbSecretKey);
                                    break;
                                }
                            default:
                                break;
                        }
                    }
                }
            }

            if (m_xameleonConfiguration.DebugMode == "yes")
                m_DEBUG = true;

            if (m_xameleonConfiguration.UseMemcached == "yes")
            {
                m_useMemCached = true;
                m_memcachedClient = new Client(new MemcachedClient(), AspNetMemcachedConfiguration.GetConfig());
            }

            string baseUri = (string)m_xameleonConfiguration.PreCompiledXslt.BaseUri;
            if (baseUri != String.Empty)
                baseUri = (string)m_xameleonConfiguration.PreCompiledXslt.BaseUri;
            else
                baseUri = "~";

            m_xsltTransformationManager = new XsltTransformationManager(m_processor, m_transform, m_resolver, m_serializer);
            m_xsltTransformationManager.HashAlgorithm = m_hashAlgorithm;
            m_resolver.Credentials = CredentialCache.DefaultCredentials;
            m_namedXsltHashtable = m_xsltTransformationManager.NamedXsltHashtable;

            foreach (PreCompiledXslt xslt in m_xameleonConfiguration.PreCompiledXslt)
            {
                string localBaseUri = (string)m_xameleonConfiguration.PreCompiledXslt.BaseUri;
                if (localBaseUri == String.Empty)
                    localBaseUri = baseUri;
                Uri xsltUri = new Uri(HttpContext.Current.Server.MapPath(localBaseUri + xslt.Uri));
                m_xsltTransformationManager.Compiler.BaseUri = xsltUri;
                m_xsltTransformationManager.AddTransformer(xslt.Name, xsltUri, m_resolver, xslt.InitialMode, xslt.InitialTemplate);
                m_namedXsltHashtable.Add(xslt.Name, xsltUri);
                if (xslt.UseAsBaseXslt == "yes")
                {
                    m_baseXsltContext = new BaseXsltContext(xsltUri, XsltTransformationManager.GenerateNamedETagKey(xslt.Name, xsltUri), xslt.Name);
                }
            }

            m_xsltTransformationManager.SetBaseXsltContext(m_baseXsltContext);

            foreach (XsltParam xsltParam in m_xameleonConfiguration.GlobalXsltParam)
            {
                m_globalXsltParams[xsltParam.Name] = (string)xsltParam.Select;
            }

            if (m_memcachedClient != null)
                Application["as_memcached"] = m_memcachedClient;
            Application["as_usememcached"] = m_useMemCached;
            Application["as_xslTransformationManager"] = m_xsltTransformationManager;
            Application["as_xmlServiceOperationManager"] = m_xmlServiceOperationManager;
            Application["as_namedXsltHashtable"] = m_namedXsltHashtable;
            Application["as_globalXsltParams"] = m_globalXsltParams;
            Application["as_geoIPLookup"] = m_geoIPLookup;
            Application["as_debug"] = m_DEBUG;
            Application["as_hashkey"] = hashkey;
            Application["as_encoding"] = m_encoding;
            Application["as_pledgeCount"] = m_pledgeCount;
            Application["as_pledgeQueue"] = m_pledgeQueue;
        }
Exemplo n.º 15
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();

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

            // Define a stylesheet that generates messages
            String stylesheet =
                "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='2.0'>\n" +
                "<xsl:template name='main'>\n" +
                "  <xsl:message><a>starting</a></xsl:message>\n" +
                "  <out><xsl:value-of select='current-date()'/></out>\n" +
                "  <xsl:message><a>finishing</a></xsl:message>\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 name of the initial template
            transformer.InitialTemplate = new QName("", "main");

            // Create a Listener to which messages will be written
            transformer.MessageListener = new UserMessageListener();

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

            // Transform the source XML to System.out.
            transformer.Run(serializer);
        }
Exemplo n.º 16
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());
     }
 }
Exemplo n.º 17
0
 public XsltTransformationManager (Processor processor, Transform transform, XmlUrlResolver resolver, Serializer serializer)
     : this(processor, transform, resolver, serializer, new Dictionary<string, XsltTransformer>(), new Hashtable(), new Hashtable(), new Hashtable(), new Hashtable(), new Hashtable(), null, null, null) {
 }
Exemplo n.º 18
0
        /// <summary>
        /// Run an XSLT transformation producing multiple output documents
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();
            processor.SetProperty("http://saxon.sf.net/feature/timing", "true");

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

            // Create a transformer for the stylesheet.
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(samplesDir, "styles/play.xsl")).Load();

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

            // Set the required stylesheet parameter
            transformer.SetParameter(new QName("", "", "dir"), new XdmAtomicValue(samplesDir.ToString() + "play"));

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

            // Transform the source XML to System.out.
            transformer.Run(serializer);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Show a query producing a document as its result and serializing this to a FileStream
 /// </summary>
 public override void run(Uri samplesDir)
 {
     Processor processor = new Processor();
     XQueryCompiler compiler = processor.NewXQueryCompiler();
     compiler.BaseUri = samplesDir.ToString();
     compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
     XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
     XQueryEvaluator eval = exp.Load();
     Serializer qout = new Serializer();
     qout.SetOutputProperty(Serializer.METHOD, "xml");
     qout.SetOutputProperty(Serializer.INDENT, "yes");
     qout.SetOutputProperty(Serializer.SAXON_INDENT_SPACES, "1");
     qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
     Console.WriteLine("Output written to testoutput.xml");
     eval.Run(qout);
 }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Demonstrate XQuery extensibility using user-written extension functions
        /// </summary>
        /// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesPE, use 
        /// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE
        /// </remarks>
        public override void run(Uri samplesDir)
        {
            String query =
                "declare namespace ext = \"clitype:SampleExtensions.SampleExtensions?asm=ExamplesPE\";" +
                "<out>" +
                "  <addition>{ext:add(2,2)}</addition>" +
                "  <average>{ext:average((1,2,3,4,5,6))}</average>" +
                "  <language>{ext:hostLanguage()}</language>" +
                "</out>";

            Processor processor = new Processor();
            XQueryCompiler compiler = processor.NewXQueryCompiler();
            XQueryExecutable exp = compiler.Compile(query);
            XQueryEvaluator eval = exp.Load();
            Serializer qout = new Serializer();
            eval.Run(qout);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
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");
        }
Exemplo n.º 25
0
        /// <summary>
        /// Demonstrate XSLT extensibility using user-written extension functions
        /// </summary>
        /// <remarks>Note: If SamplesExtensions is compiled to a different assembly than ExamplesPE, use 
        /// the namespace URI clitype:SampleExtensions.SampleExtensions?asm=ASSEMBLY_NAME_HERE
        /// </remarks>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Identify the Processor version
            Console.WriteLine(processor.ProductVersion);

            // Set diagnostics
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");

            // Create the stylesheet
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
                @" xmlns:ext='clitype:SampleExtensions.SampleExtensions?asm=ExamplesPE' " +
                @" xmlns:tz='clitype:System.TimeZone' " +
                @" xmlns:math='http://example.math.co.uk/demo' " +
                @" xmlns:env='http://example.env.co.uk/demo' " +
                @" exclude-result-prefixes='ext math env tz'> " +
                @" <xsl:param name='timezone' required='yes'/> " +
                @" <xsl:template match='/'> " +
                @" <out addition='{ext:add(2,2)}' " +
                @" average='{ext:average((1,2,3,4,5,6))}' " +
                @" firstchild='{ext:nameOfFirstChild(.)}' " +
                @" timezone='{tz:StandardName($timezone)}' " +
                @" sqrt2='{math:sqrt(2.0e0)}' " +
                @" defaultNamespace='{env:defaultNamespace()}' " +
                @" sqrtEmpty='{math:sqrt(())}'> " +
                @" <xsl:copy-of select='ext:FirstChild((//ITEM)[1])'/> " +
                @" <defaultNS value='{env:defaultNamespace()}' xsl:xpath-default-namespace='http://default.namespace.com/' /> " +
                @" <combine1><xsl:sequence select='ext:combine(ext:FirstChild((//ITEM)[1]), count(*))'/></combine1> " +
                @" <combine2><xsl:sequence select='ext:combine((//TITLE)[1], (//AUTHOR)[1])'/></combine2> " +
                @" </out> " +
                @" </xsl:template></xsl:transform>";

            // Register the integrated extension functions math:sqrt and env:defaultNamespace

            processor.RegisterExtensionFunction(new Sqrt());
            processor.RegisterExtensionFunction(new DefaultNamespace());

            // Create a transformer for the stylesheet.
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();

            // Load the source document (must be a wrapper around an XmlDocument for this test)
            XmlDocument doc = new XmlDocument();
            doc.Load(new XmlTextReader(samplesDir.AbsolutePath + "data/books.xml"));
            XdmNode input = processor.NewDocumentBuilder().Wrap(doc);

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

            // Supply a parameter
            transformer.SetParameter(new QName("", "timezone"),
                      XdmAtomicValue.WrapExternalObject(TimeZone.CurrentTimeZone));

            // Create a serializer
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(Console.Out);
            serializer.SetOutputProperty(Serializer.INDENT, "yes");

            // Transform the source XML to System.out.
            transformer.Run(serializer);
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
0
        public override void run(Uri samplesDir)
        {
            String query = "xquery version '1.1'; try {doc('book.xml')}catch * {\"XQuery 1.1 catch clause - file not found.\"}";
            Processor processor = new Processor();

            XQueryCompiler compiler = processor.NewXQueryCompiler();
            compiler.XQueryLanguageVersion = "1.1";
            XQueryExecutable exp = compiler.Compile(query);
            XQueryEvaluator eval = exp.Load();
            Serializer qout = new Serializer();
            eval.Run(qout);
        }
Exemplo n.º 28
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);
        }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Show a transformation using calls to extension functions
        /// </summary>
        public override void run(Uri samplesDir)
        {
            // Create a Processor instance.
            Processor processor = new Processor();

            // Identify the Processor version
            Console.WriteLine(processor.ProductVersion);

            // Set diagnostics
            //processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true");

            // Create the stylesheet
            String s = @"<xsl:transform version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
                @" xmlns:math='http://example.math.co.uk/demo'> " +
                @" <xsl:template name='go'> " +
                @" <out sqrt2='{math:sqrt(2.0e0)}' " +
                @" sqrtEmpty='{math:sqrt(())}'/> " +
                @" </xsl:template></xsl:transform>";

            // Register the integrated extension function math:sqrt

            processor.RegisterExtensionFunction(new Sqrt());

            // Create a transformer for the stylesheet.
            XsltTransformer transformer = processor.NewXsltCompiler().Compile(new StringReader(s)).Load();

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

            // Create a serializer
            Serializer serializer = new Serializer();
            serializer.SetOutputWriter(Console.Out);
            serializer.SetOutputProperty(Serializer.INDENT, "yes");

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