Home > C#, XML > C#: Get indented xml-based string

C#: Get indented xml-based string

January 18th, 2012 Leave a comment Go to comments

    Manipulating XmlNodes we can get the result xml-based string using the InnerXml property of the XmlDocument-object the XmlNodes belong to. For example,

using System;
using System.Xml;
using System.IO;
...
// create XmlDocument object
XmlDocument xmlDOc = new XmlDocument();
xmlDOc.LoadXml(@"<rootNode><firstChildNode name=""first"" /></rootNode>");            

// manipulate with its nodes
XmlNode secondChildNode = xmlDOc.CreateElement("secondChildNode");
XmlAttribute nameAttr = xmlDOc.CreateAttribute("name");
nameAttr.Value = "secondChildNode";
secondChildNode.Attributes.Append(nameAttr);
XmlNode rootNode = xmlDOc.SelectSingleNode("/rootNode");
rootNode.AppendChild(secondChildNode);

// get the result xml-based string
string result = xmlDOc.InnerXml;

The following string is obtained:

<rootNode><firstChildNode name="first" /><secondChildNode name="secondChildNode" /></rootNode>

However, very often the result xml-based string is required to be formatted with indentations as it looks in many xml editors. The following method can be used for this:

public static string XmlDocToString(XmlDocument xmlDoc)
{
    StringWriter sw = new StringWriter();
    XmlTextWriter xw = new XmlTextWriter(sw);
    xw.Formatting = Formatting.Indented;
    xmlDoc.WriteTo(xw);
    return sw.ToString();
}

I usually use this method before displaying or saving the string in file. The indented result looks like:

<rootNode>
  <firstChildNode name="first" />
  <secondChildNode name="secondChildNode" />
</rootNode>

How to use:

string formattedStr = XmlDocToString(xmlDOc);
 
Categories: C#, XML Tags: ,
  1. No comments yet.
  1. No trackbacks yet.