Simplest way to transform XML to HTML with XSLT in C#?

后端 未结 2 1180
梦毁少年i
梦毁少年i 2020-12-02 12:41

XSLT newbie question: Please fill in the blank in the C# code fragment below:

public static string TransformXMLToHTML(string inputXml, string xsltString) {
          


        
相关标签:
2条回答
  • 2020-12-02 13:13

    How about:

    public static string TransformXMLToHTML(string inputXml, string xsltString)
    {
        XslCompiledTransform transform = new XslCompiledTransform();
        using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) {
            transform.Load(reader);
        }
        StringWriter results = new StringWriter();
        using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) {
            transform.Transform(reader, null, results);
        }
        return results.ToString();
    }
    

    Note that ideally you would cache and re-use the XslCompiledTransform - or perhaps use XslTransform instead (it is marked as deprecated, though).

    0 讨论(0)
  • 2020-12-02 13:14

    Just for fun, a slightly less elegant version that implements the caching suggested by Marc:

        public static string TransformXMLToHTML(string inputXml, string xsltString)
        {
            XslCompiledTransform transform = GetAndCacheTransform(xsltString);
            StringWriter results = new StringWriter();
            using (XmlReader reader = XmlReader.Create(new StringReader(inputXml)))
            {
                transform.Transform(reader, null, results);
            }
            return results.ToString();
        }
    
        private static Dictionary<String, XslCompiledTransform> cachedTransforms = new Dictionary<string, XslCompiledTransform>();
        private static XslCompiledTransform GetAndCacheTransform(String xslt)
        {
            XslCompiledTransform transform;
            if (!cachedTransforms.TryGetValue(xslt, out transform))
            {
                transform = new XslCompiledTransform();
                using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
                {
                    transform.Load(reader);
                }
                cachedTransforms.Add(xslt, transform);
            }
            return transform;
        }
    
    0 讨论(0)
提交回复
热议问题