Un esempio C# di come identare correttamente una stringa contenente una struttura XML
C#
private string IndentXMLString(string xml)
{
  System.Text.StringBuilder sb = new System.Text.StringBuilder(1000);
  using (System.IO.TextReader tReader = new System.IO.StringReader(xml))
  {
    System.Xml.XmlReader reader = System.Xml.XmlReader.Create(tReader);
    System.Xml.Linq.XDocument xDoc = System.Xml.Linq.XDocument.Load(reader);

    System.Xml.XmlWriterSettings s = new System.Xml.XmlWriterSettings();
    s.Indent = true;
    System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(sb, s);
    xDoc.Save(wr);
    wr.Flush(); // da non dimenticare !!!
  }
  return sb.ToString();
}
passando una stringa che contiene
XML
<rootNode><elm id="1" /><elm id="2"><chd name="xd1" /></elm></rootNode>
ritorna una string identata
XML
<rootNode>
  <elm id="1" />
  <elm id="2">
    <chd name="xd1" />
  </elm>
</rootNode>
Potrebbe interessarti anche: