Search code examples
c#xmlautoformatting

Autoformat XML string/stream programmatically


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);

Solution

  • use XDocument and load the steam

    XDocument doc= XDocument.Load(stream);
    
    Debug.WriteLine(doc.ToString());