In native programming the IXMLDOMDocument2 object had a tranformNode()
method:
public BSTR transformNode(IXMLDOMNode stylesheet);
So in the end i could tranform an XML document using:
public string TransformDocument(IXMLDOMDocument2 doc, IXMLDOMDocument2 stylesheet)
{
return doc.TransformNode(stylesheet);
}
i'm trying to find the managed equivalent. i've already discovered XmlDocument object:
public string TransformDocument(XmlDocument doc, XmlDocument stylesheet)
{
//return doc.TransformNode(stylesheet); //TransformNode not supported
}
So what is the managed way to tranform xml?
i've stumbled across the depricated XslTransform object, but none of the 18 overloads takes an xml document, or an xml stylesheet.
The replacment Microsoft indicates is the mouthful: System.Xml.Xsl.XslCompiledTransform. But like it's depricated cousin, none of XslCompiledTransform's 14 overloads takes xml in an input parameter.
So what's the accepted method to transform xml in C# .NET 2.0?
Put it another way: complete the following helper method:
public string TransformDocument(XmlDocument doc, XmlDocument stylesheet)
{
//todo: figure out how to transform xml in C#
}
Answer
Waqas had the answer. Here is another, very similiar, solution:
/// <summary>
/// This method simulates the XMLDOMDocument.TransformNode method
/// </summary>
/// <param name="doc">XML document to be transformed</param>
/// <param name="stylesheet">The stylesheet to transform with</param>
/// <returns></returns>
public static string Transform(XmlDocument doc, XmlDocument stylesheet)
{
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(stylesheet); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
transform.Transform(doc, XmlWriter.Create(writer));
return writer.ToString();
}
Note: If you're a performance weenie, you might want to create an overload to pass the pre-compiled transform, if you're going to transforming more than once.
public static string Transform(XmlDocument doc, XslCompiledTransform stylesheet)
{
...
}