.NET: XSLT transformation with formatted XML output (with indents and new lines)

Suppose you need to transform one XML string into another XML string. And output XML must be formatted: with new lines and indents. So you can do it like this:

/// 
/// Transforms one XML-string() into another XML-string
/// using XSLT file()
/// 
/// Input XML string
/// XSLT file name
/// Transformed and formatted XML-string
public static string Transform(string source, string xsltFileName)
{
    //Read the xml string into XPathDocument
    XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(source));
    XPathDocument xPathDoc = new XPathDocument(xmlTextReader);
    //Create and load transform from file
    XslCompiledTransform xslTransform = new XslCompiledTransform();
    xslTransform.Load(xsltFileName);
    //Create a writer for writing the transformed file
    StringBuilder sb = new StringBuilder();
    XmlTextWriter xmlTextWriter = new XmlTextWriter(new StringWriter(sb));
    //Do the transformation
    xslTransform.Transform(xPathDoc, xmlTextWriter);
    //Format output with indent and new lines via XDocument
    return XDocument.Parse(sb.ToString()).ToString();
}

Note: Here we do not consider the questions of performance. If you need better performance you can play with xslt.

Rating: