Reading XML file and indenting

[亡魂溺海] 提交于 2019-12-11 03:14:08

问题


I've been having problems with the indentation of my XML files. Everytime I load them from a certain server, the XML nodes all jumble up on a few lines. I want to write a quick application to indent the nodes properly. That is:

<name>Bob<name>
<age>24</age>
<address>
  <stnum>2</stnum>
  <street>herp derp st</street>
</address>

currently it's coming out as :

<name>bob</name><age>24</age>
<address>
      <stnum>2</stnum><street>herp derp st</street>
</address>

since I can't touch the internal program that gives me these xml files and re-indenting them without a program would take ages, I wanted to write up a quick program to do this for me. When I use the XMLdocument library stuff, it only reads the information of the nodes. So my question is, whats a good way to read the file, line by line and then reindenting it for me. All xml nodes are the same.

Thanks.


回答1:


You can use the XmlTextWritter class. More specifically the .Formatting = Formatting.Indented.

Here is some sample code I found on this blog post. http://www.yetanotherchris.me/home/2009/9/9/formatting-xml-in-c.html

public static string FormatXml(string inputXml)
{
    XmlDocument document = new XmlDocument();
    document.Load(new StringReader(inputXml));

    StringBuilder builder = new StringBuilder();
    using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder)))
    {
        writer.Formatting = Formatting.Indented;
        document.Save(writer);
    }

    return builder.ToString();
}



回答2:


With LINQ to XML, it's basically a one-liner:

public static string Reformat(string xml)
{
    return XDocument.Parse(xml).ToString();
}



回答3:


Visual Studio or any decent XML editor will format (tabify) XML documents easily. There are also on-line tools available:

http://www.xmlformatter.net/

http://www.shell-tools.net/index.php?op=xml_format




回答4:


If you are using Visual studio just open xml do Ctrl+a Ctrl+k Ctrl+F and that's it for formatting.




回答5:


You can also use XSLT:

  // This XSLT copies everything but idented

  StringReader sr = new StringReader( xsl );
  XmlReader reader = XmlReader.Create(sr);
  XslTransform xslt = new XslTransform();
  xslt.Load(reader);
  xslt.Transform(xmlFileUnidentedPath, xmlFileIdentedPath);

Having xsl defined as:

string xsl = @"
<?xml version=""1.0""?>
<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:output method=""xml"" omit-xml-declaration=""no"" indent=""yes"" encoding=""US-SCII""/>
<xsl:strip-space elements=""*""/>
<xsl:template match=""/"">
  <xsl:copy-of select="".""/>
</xsl:template>
</xsl:stylesheet>";


来源:https://stackoverflow.com/questions/9205073/reading-xml-file-and-indenting

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