0

Whats the best way to turn some Xml into a well indented/formatted Xml and access the individual lines of the resulting Xml afterwards? I guess the first part of the problem (indenting/formatting) can be solved using an XmlTextWriter or something similar. But how do I get an array of lines out of the result? Do I have to split the string again? Are there more elegant options?

Thanks in advance!

leppie
  • 115,091
  • 17
  • 196
  • 297
Mats
  • 14,902
  • 33
  • 78
  • 110

1 Answers1

0

How to pretty print XML?

string FormatXml(String Xml)
{
     try
     {
         XDocument doc = XDocument.Parse(Xml);
         return doc.ToString();
     }
     catch (Exception)
     {
         return Xml;
     }
 }

Alternative is: https://stackoverflow.com/a/203581/1163786

How to build an array with lines from the XML?

string[] lines = xml.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

Are there more elegant options?

That depends on what "elegant" means to you. If you find regular expressions elegant and powerful, then the solution above is amongst the elegant solutions. If you prefer non-regexp solutions, then utilizing the StringReader might be worth looking into:

using (System.IO.StringReader reader = new System.IO.StringReader(xml)) {
    string[] lines = = reader.ReadLine();
}
Community
  • 1
  • 1
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141