I am trying to use a XslCompiledTransform, and use the output as a XPathDocument.
Any Ideas?
I am trying to use a XslCompiledTransform, and use the output as a XPathDocument.
Any Ideas?
Send the transform to an XmlTextWriter
based on a StringWriter
. Then instance the XPathDocument
by retreiving the XML string from the StringWriter
.
var sw = new StringWriter();
var xtw = new XmlTextWriter(sw);
myTransform.Transform(myXml, xtw);
var xpd = new XPathDocument(sw.ToString());
Its not the most memory efficient mechanism but will be adequate for most needs. A similar approach would be use a MemoryStream
instead of a StringWriter
but its a little messy by comparison.
Mr. Jones's answer was very helpful for me, but I found that the last line didn't work. I ended up doing this:
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);
(Here, xPathDoc is an XPathDocument that has already been initialized from an XmlReader.)
A slightly better form of David M. Anderson's answer is below: it does not suffer from potential resource leaks; otherwise it is the same.
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);
}
}
}