views:

341

answers:

3

I am trying to use a XslCompiledTransform, and use the output as a XPathDocument.

Any Ideas?

+2  A: 

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.

AnthonyWJones
+2  A: 

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.)

David M. Anderson
+1  A: 

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);
        }
    }
}
John Saunders