Micha
Micha

Reputation: 61

C#: A simple way to bring One-line-XML-files to human readable multi line

I'm looking for a simply way to bring a xml-File with one line without line feeds to a good structured human readable version in C#. Is there any Implementation already in System.XML or a tiny open source framework or a best practice for implementing it?

ex. transform this XML-String:


<Root><Node id="1"><Childnode>Text</Childnode></Node><Node id="2">Text<Kid name="jack" /></Node></Root>

to


<Root>
  <Node id="1">
    <Childnode>
      Text
    </Childnode>
  </Node>
  <Node id="2">
    Text
    <Kid name="jack" />
  </Node>
</Root>

Upvotes: 3

Views: 6088

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502476

If you have .NET 3.5:

XDocument document = XDocument.Load(filename);
document.Save(filename);

This will indent automatically. Note that it won't do quite as your question asked, because you're only indenting some of the nodes. That's going to be trickier.

If you're stuck with .NET 2.0, here's Craig's method rejigged and changed to use files instead of strings:

public static void FormatXmlString(string inputFile, string outputFile)
{
    XmlDocument document = new XmlDocument();
    document.Load(inputFile);
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    using (XmlWriter writer = XmlWriter.Create(outputFile, settings))
    {
        document.WriteTo(writer);
    }
}

With C# 3 the XmlWriterSettings but could just be:

new XmlWriterSettings { Indent = true }

which could be embedded in the call to XmlWriter.Create, but if you're using .NET 2.0 you probably can't use C# 3.

EDIT: If the input filename part causes a problem, you can use:

XmlDocument document = new XmlDocument();
using (Stream stream = File.OpenRead(inputFile))
{
    document.Load(stream);
}

Upvotes: 8

CraigTP
CraigTP

Reputation: 44939

Here's a handy "FormatXML" class that I wrote for just this purpose:

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

public static class FormatXML
{
    public static string FormatXMLString(string sUnformattedXML)
    {
        XmlDocument xd = new XmlDocument();
        xd.LoadXml(sUnformattedXML);
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        XmlTextWriter xtw = null;
        try
        {
            xtw = new XmlTextWriter(sw);
            xtw.Formatting = Formatting.Indented;
            xd.WriteTo(xtw);
        }
        finally
        {
            if(xtw!=null)
                xtw.Close();
        }
        return sb.ToString();
    }
}

Upvotes: 4

alexn
alexn

Reputation: 59002

If you have got Visual Studio:

Create a new XML file and just paste your code. It will re-format it automatically.

Upvotes: 3

Related Questions