Formatting XML - Passing XmlReader to an XmlWriter

What is the best way to format and Xml string fragment

I have an Xml string fragment that is un-formated, i.e. no carriage returns or indents, etc.. I need to display the Xml on a form with indenting, in a normal beautified fassion. What would be the best way to do that

I thought I might be able to pass an XmlReader to and XmlWriter with the appropriate 2.0 XmlWriterSettings but this does not seem to work. Can someone tell me how best to accomplish this Code example below:

public static String GetFormatedMessageForDisplay(String xmlFragment)

{

XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();

xmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment;

xmlWriterSettings.Encoding = Encoding.ASCII;

xmlWriterSettings.Indent = true;

xmlWriterSettings.NewLineHandling = NewLineHandling.Entitize;

xmlWriterSettings.NewLineOnAttributes = false;

xmlWriterSettings.OmitXmlDeclaration = true;

StringBuilder sbOut = new StringBuilder();

XmlWriter xmlTextWriter = XmlTextWriter.Create(sbOut, xmlWriterSettings);

sbOut.Append(xmlFragment);

xmlTextWriter.Flush();

return sbOut.ToString();

}

Thanks!




Answer this question

Formatting XML - Passing XmlReader to an XmlWriter

  • J. Clark

    Here is one possible way to do it, using DOM and an XmlDocumentFragment node and its WriteTo method:

    using System;
    using System.IO;
    using System.Xml;

    namespace Test {
    public class Program {
    public static void Main (string[] args) {
    string xmlFragment = "<god><name>Kibo</name></god><god><name>Xibo></name></god>";

    Console.WriteLine(GetFormattedMessageForDisplay(xmlFragment));
    }

    public static string GetFormattedMessageForDisplay (string xmlFragment) {
    XmlDocument dummyDoc = new XmlDocument();
    XmlDocumentFragment docFragment = dummyDoc.CreateDocumentFragment();
    docFragment.InnerXml = xmlFragment;
    XmlWriterSettings writerSettings = new XmlWriterSettings();
    writerSettings.Indent = true;
    writerSettings.ConformanceLevel= ConformanceLevel.Fragment;
    StringWriter stringWriter = new StringWriter();
    using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings)) {
    docFragment.WriteTo(xmlWriter);
    }
    return stringWriter.ToString();
    }
    }
    }

    It is of course possible to do that with just XmlReader and XmlWriter but you need to write code then that uses the reader to pull in nodes and the writer to write out the equivalent output for each node, that will take more lines than the above.



  • Dmitry Radich

    Yes, Thank you! That does the trick.

    I was thinking that there might be an easy way to simply pass the output of an XmlReader to an XmlWriter with the appropriate settings. But this solution will work fine for what I'm doing...

    Thanks again for the help...



  • Formatting XML - Passing XmlReader to an XmlWriter