我正在尝试使用XslCompiledTransform,并将输出用作XPathDocument。
任何想法?
答案 0 :(得分:3)
先生。琼斯的回答对我很有帮助,但我发现最后一行没有用。我最终这样做了:
XslCompiledTransform xsl = new XslCompiledTransform();
xsl.Load(filePath);
StringWriter stringWriter = new StringWriter();
XmlWriter xmlWriter = XmlTextWriter.Create(stringWriter);
xsl.Transform(xPathDoc, xmlWriter);
String newXml = stringWriter.ToString();
StringReader stringReader = new StringReader(newXml);
xPathDoc = new XPathDocument(stringReader);
(这里,xPathDoc是一个已经从XmlReader初始化的XPathDocument。)
答案 1 :(得分:2)
根据XmlTextWriter
将转化发送至StringWriter
。然后通过从XPathDocument
恢复XML字符串来实例化StringWriter
。
var sw = new StringWriter();
var xtw = new XmlTextWriter(sw);
myTransform.Transform(myXml, xtw);
var xpd = new XPathDocument(sw.ToString());
它不是最有效的内存机制,但足以满足大多数需求。类似的方法是使用MemoryStream
而不是StringWriter
,但相比之下它有点混乱。
答案 2 :(得分:2)
稍微好一点的David M. Anderson的答案如下:它没有遭受潜在的资源泄漏;否则它是一样的。
private static XPathDocument TransformToXPathDocument(string styleSheetPath,
IXPathNavigable xPathDoc)
{
var xsl = new XslCompiledTransform();
xsl.Load(styleSheetPath);
using(var stringWriter = new StringWriter())
{
using(XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
{
xsl.Transform(xPathDoc, xmlWriter);
}
using(var reader = new StringReader(stringWriter.ToString()))
{
return new XPathDocument(reader);
}
}
}