Autoformat XML string/stream programmatically

175 views Asked by At

I have a valid xml stream and want to write this stream to debug output in an easy readable way.

At the moment I get something like this:

<bla><yadda>hello</yadda><yadda>world</yadda></bla>

But what I want is this:

<bla>
    <yadda>hello</yadda>
    <yadda>world</yadda>
</bla>

Is there an easy way to do this?

Here is my code so far:

stream.Position = 0;
byte[] bbb = stream.GetBuffer();
string str = "";
for(int i = 0; i < stream.Length; i++)
{
  byte b = bbb[i];
  str += Convert.ToChar(b).ToString();
}
Debug.WriteLine(str);
5

There are 5 answers

0
Damith On BEST ANSWER

use XDocument and load the steam

XDocument doc= XDocument.Load(stream);

Debug.WriteLine(doc.ToString());
0
Ehsan On

this should work

string xml = "<bla><yadda>hello</yadda><yadda>world</yadda></bla>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc.ToString());

OUTPUT

<bla>
   <yadda>hello</yadda>
   <yadda>world</yadda>
</bla> 
0
Oscar On

You can use Tidy.Net library for this. It allow you to:

  • break-before-br

    indent

    indent-attributes

    indent-spaces

    markup

    punctuation-wrap

    sort-attributes

    split

    tab-size

    vertical-space

    wrap

    wrap-asp

    wrap-attributes

    wrap-jste

    wrap-php

    wrap-script-literals

    wrap-sections

http://tidy.sourceforge.net/docs/quickref.html

0
Rex On

another way is to use System.Xml.Linq.XElement:

var xel = System.Xml.Linq.XElement.Parse("<bla><yadda>hello</yadda><yadda>world</yadda></bla>");
Console.WriteLine(xel);
1
No Idea For Name On

this works as well:

StreamReader strm = new StreamReader(@"D:\\maoh.xml");

while (strm.EndOfStream == false)
{
     Console.WriteLine(strm.ReadLine());
}

and gives:

enter image description here