Xsl Transform - CSharp System.Xml

CSharp examples for System.Xml:XML Transform

Description

Xsl Transform

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Xml;
using System.Text;
using System.Security.Policy;
using System.Reflection;
using System.IO;/* w ww.  java 2  s.  c  o  m*/
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics;
using System.Collections;
using System;

public class Main{
        public static Stream XslTransform(string resource, Stream input, params DictionaryEntry[] entries)
        {
            int t1 = Environment.TickCount;

            Stream s = Util.GetEmbeddedResourceStream(resource);

            int t2 = Environment.TickCount;
            XPathDocument d = new XPathDocument(s);

            int t3 = Environment.TickCount;
            XslCompiledTransform xslc = new XslCompiledTransform();
            // Using the Trusted Xslt is fine as the style sheet comes from our own assemblies.
            // This is similar to the prior this.GetType().Assembly/Evidence method that was used in the now depricated XslTransform.
            xslc.Load(d, XsltSettings.TrustedXslt, s_resolver);

            // Need to copy input stream because XmlReader will close it,
            // causing errors for later callers that access the same stream
            MemoryStream clonedInput = new MemoryStream();
            Util.CopyStream(input, clonedInput);

            int t4 = Environment.TickCount;
            XmlReader xml = XmlReader.Create(clonedInput);

            XsltArgumentList args = null;
            if (entries.Length > 0)
            {
                args = new XsltArgumentList();
                foreach (DictionaryEntry entry in entries)
                {
                    string key = entry.Key.ToString();
                    object val = entry.Value.ToString();
                    args.AddParam(key, "", val);
                    Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "arg: key='{0}' value='{1}'", key, val.ToString()));
                }
            }

            MemoryStream m = new MemoryStream();
            XmlTextWriter w = new XmlTextWriter(m, Encoding.UTF8);
            w.WriteStartDocument();

            int t5 = Environment.TickCount;
            xslc.Transform(xml, args, w, s_resolver);

            w.WriteEndDocument();
            w.Flush();
            m.Position = 0;

            return m;
        }
}

Related Tutorials