如何使用 .NET 中的文件将 XML 转换为不带字符串的字符串? [英] How to transform XML as a string w/o using files in .NET?
问题描述
假设我有两个字符串:
- 一个是 XML 数据
- 另一个是XSL数据.
xml 和 xsl 数据存储在数据库列中,如果您必须知道的话.
The xml and xsl data are stored in database columns, if you must know.
如何在 C# 中转换 XML,而无需先将 xml 和 xsl 保存为文件?我也希望输出是一个字符串(来自转换的 HTML).
How can I transform the XML in C# w/o saving the xml and xsl as files first? I would like the output to be a string, too (HTML from the transformation).
似乎 C# 更喜欢通过文件进行转换.我在 XslCompiledTransform 中找不到 Load() 的字符串输入重载.所以,这就是我问的原因.
It seems C# prefers to transform via files. I couldn't find a string-input overload for Load() in XslCompiledTransform. So, that's why I'm asking.
推荐答案
这是我的想法.这是您的答案的组合.我投票赞成激发这一点的答案:
Here's what I went with. It's a combination of your answers. I voted up the answers that inspired this:
string output = String.Empty;
using (StringReader srt = new StringReader(xslInput)) // xslInput is a string that contains xsl
using (StringReader sri = new StringReader(xmlInput)) // xmlInput is a string that contains xml
{
using (XmlReader xrt = XmlReader.Create(srt))
using (XmlReader xri = XmlReader.Create(sri))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
using (StringWriter sw = new StringWriter())
using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
{
xslt.Transform(xri, xwo);
output = sw.ToString();
}
}
}
注意:在 xsl 中需要此语句,以便输出为 HTML:
Note: this statement is required in the xsl, in order to output as HTML:
<xsl:output method="html" omit-xml-declaration="yes" />
这篇关于如何使用 .NET 中的文件将 XML 转换为不带字符串的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!