【问题标题】:Autoformat XML string/stream programmatically以编程方式自动格式化 XML 字符串/流
【发布时间】:2013-08-27 07:03:26
【问题描述】:

我有一个有效的 xml 流,并希望以一种易于阅读的方式编写此流以调试输出。

目前我得到这样的东西:

<bla><yadda>hello</yadda><yadda>world</yadda></bla>

但我想要的是这样的:

<bla>
    <yadda>hello</yadda>
    <yadda>world</yadda>
</bla>

有没有简单的方法可以做到这一点?

到目前为止,这是我的代码:

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

【问题讨论】:

    标签: c# xml autoformatting


    【解决方案1】:

    这应该可以工作

    string xml = "<bla><yadda>hello</yadda><yadda>world</yadda></bla>";
    XDocument doc = XDocument.Parse(xml);
    Console.WriteLine(doc.ToString());
    

    输出

    <bla>
       <yadda>hello</yadda>
       <yadda>world</yadda>
    </bla> 
    

    【讨论】:

      【解决方案2】:

      使用XDocument 并加载蒸汽

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

      【讨论】:

      • 正是我想要的。谢谢。
      【解决方案3】:

      另一种方法是使用System.Xml.Linq.XElement:

      var xel = System.Xml.Linq.XElement.Parse("<bla><yadda>hello</yadda><yadda>world</yadda></bla>");
      Console.WriteLine(xel);
      

      【讨论】:

        【解决方案4】:

        这也有效:

        StreamReader strm = new StreamReader(@"D:\\maoh.xml");
        
        while (strm.EndOfStream == false)
        {
             Console.WriteLine(strm.ReadLine());
        }
        

        并给出:

        【讨论】:

        • 亲爱的@NoOne,感谢您的编辑,但请不要编辑代码,只是编队。我知道它是一样的,但仍然......我这样写是有原因的。
        【解决方案5】:

        您可以为此使用 Tidy.Net 库。它允许您:

        • 先休息

          缩进

          缩进属性

          缩进空格

          标记

          标点换行

          排序属性

          拆分

          标签大小

          垂直空间

          包装

          包装-asp

          包装属性

          包装-jste

          包装-php

          包装脚本文字

          包装部分

        http://tidy.sourceforge.net/docs/quickref.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-17
          相关资源
          最近更新 更多