使用C#中的XSLT将XML转换为HTML的最简单方法?

时间:2009-11-22 09:48:18

标签: c# xslt

XSLT新手问题:请填写下面C#代码片段中的空白:

public static string TransformXMLToHTML(string inputXml, string xsltString) {
  // insert code here to apply the transform specified by xsltString to inputXml 
  // and return the resultant HTML string.
  // You may assume that the xslt output type is HTML.
}

谢谢!

2 个答案:

答案 0 :(得分:38)

怎么样:

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();
}

请注意,理想情况下,您可以缓存并重新使用XslCompiledTransform - 或者使用XslTransform代替(虽然已将其标记为已弃用)。

答案 1 :(得分:4)

只是为了好玩,一个稍微不那么优雅的版本实现了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;
    }