Make xml more readable

为君一笑 提交于 2019-12-03 15:54:25

If you're using .NET 3.5, you can load it as an XDocument and then just call ToString() which will indent it appropriately. For example:

using System;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        string xml = "<element1><element2>some data</element2></element1>";

        XDocument doc = XDocument.Parse(xml);
        xml = doc.ToString();
        Console.WriteLine(xml);
    }
}

Result:

<element1>
  <element2>some data</element2>
</element1>

If you're writing it to a file or other stream, then XDocument.Save will (by default) indent it too.

(I believe XElement has all the same features, if you don't really need an XDocument.)

How do you save / write the XML back to a file ?

You can create an XmlWriter and pass it an XmlWriterSettings instance, where you set the Indent property to true:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

XmlWriter writer = XmlWriter.Create (outputStream, settings);

You can load the string into an XDocument object and save it to a string again:

XDocument doc = XDocument.Load(new StringReader(xmlString));
StringWriter writer = new StringWriter();
doc.Save(writer);
string readable = writer.ToString();

That will give you the xml formatted this way:

<?xml version="1.0" encoding="utf-16"?>
<element1>
    <element2>some data</element2>
</element1>

Have a look at

XmlWriterSettings

http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx

you can define Indent and IndentChars

First of all, you have tagged C# and VB.NET both. So my answer will be for both of them.

You can define function which get XML string as a parameter in type of String.

Let's say;

You created a function as :

[VB]

Private Function PrettyXML(XMLString As String) As String    
      Dim sw As New StringWriter()
      Dim xw As New XMLWriter(sw)
      xw.Formatiing = Formatting.Indented
      xw.Indentation = 4

      Dim doc As New XMLDocument
      doc.LoadXML(XMLString)
      doc.Save(xw)
      Return sw.ToString()    
End Function

Then you can simpyl call this function as:

Dim myXML As String = "<element1><element2>some data</element2></element1>"
Dim myPrettyXML As String
myPrettyXML = PrettyXML(myPrettyXML)

[C#]

Private String PrettyXML(string XMLString)
   {
      StringWriter sw = new StringWriter();
      XMLTextWriter xw = new XmlTextWriter(sw);
      xw.Formatiing = Formatting.Indented;
      xw.Indentation = 4;
      XmlDocument doc = new XmlDocument();
      doc.Save(xm);
      return sw.ToString();
   }

Then you can simply call this function as:

string myXML =   "<element1><element2>some data</element2></element1>";
string myPrettyXML = "";
myPrettyXML = PrettyXML(myPrettyXML);

NOTE: I have not tried C# version, but it should work.

Hope this helps..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!