读取XML文件并缩进 [英] Reading XML file and indenting

查看:268
本文介绍了读取XML文件并缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的XML文件缩进一直遇到问题.每当我从某个服务器上加载它们时,XML节点都会在几行上混杂在一起.我想编写一个快速应用程序以正确缩进节点.那就是:

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>

当前它以:

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

由于我无法触摸提供这些xml文件的内部程序,并且在没有程序的情况下重新缩进它们会花费很多时间,因此我想编写一个快速程序来为我完成此任务.当我使用XMLdocument库的东西时,它只读取节点的信息.所以我的问题是,什么是逐行读取文件然后为我重新缩进的好方法.所有xml节点都相同.

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.

谢谢.

推荐答案

您可以使用XmlTextWritter类.更具体地说,.Formatting = Formatting.Indented.

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

这是我在此博客文章中找到的一些示例代码. http://www.yetanotherchris.me/home /2009/9/9/formatting-xml-in-c.html

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

这篇关于读取XML文件并缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆