在 C# 中使用 XSLT 将 XML 转换为 HTML 的最简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1778299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest way to transform XML to HTML with XSLT in C#?
提问by Shaul Behr
XSLT newbie question: Please fill in the blank in the C# code fragment below:
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.
}
Thanks!
谢谢!
采纳答案by Marc Gravell
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).
请注意,理想情况下,您将缓存并重新使用XslCompiledTransform
- 或者可能使用XslTransform
它(尽管它被标记为已弃用)。
回答by Dathan
Just for fun, a slightly less elegant version that implements the caching suggested by Marc:
只是为了好玩,一个稍微不那么优雅的版本,它实现了 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;
}