读取XML文件并缩进
我在 XML 文件的缩进方面遇到了问题。每次我从某个服务器加载它们时,XML 节点都会在几行上混乱起来。我想编写一个快速应用程序来正确缩进节点。也就是说:
<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 节点都是相同的。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 XmlTextWritter 类。更具体地说,.Formatting = Formatting.Indented。
这是我在这篇博客文章中找到的一些示例代码。
http://www.yetanotherchris.me/home /2009/9/9/formatting-xml-in-c.html
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
对于 LINQ to XML,它基本上是一行代码:
With LINQ to XML, it's basically a one-liner:
Visual Studio 或任何合适的 XML 编辑器都可以轻松格式化(制表)XML 文档。还有一些可用的在线工具:
http://www.xmlformatter.net/
http://www.shell-tools.net/index.php?op=xml_format
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
如果您使用的是 Visual Studio,只需打开 xml,执行 Ctrl+a Ctrl+k Ctrl+F 即可进行格式化。
If you are using Visual studio just open xml do Ctrl+a Ctrl+k Ctrl+F and that's it for formatting.
您还可以使用 XSLT:
将 xsl 定义为:
You can also use XSLT:
Having xsl defined as: