【问题标题】:How do you remove blank lines from an XML document or node using C#?如何使用 C# 从 XML 文档或节点中删除空白行?
【发布时间】:2016-06-23 01:23:28
【问题描述】:

我希望在将其写入文档之前删除下面 XML 中的所有空行。知道我之前使用了 XPathNavigator 类的 .DeleteSelf() 方法来删​​除不需要的节点(并且只留下空行),这可能会有所帮助。

    <Person xmlns="http://someURI.com/something">
      <FirstName>Name1</FirstName>











       <MiddleName>Name2</MiddleName>


       <LastName>Name3</LastName>




     </Person>

【问题讨论】:

标签: c# xml xmldocument xmlnode


【解决方案1】:

我建议使用XDocument 类:

1.方法:

string xcontent = @" strange xml content here ";
XDocument xdoc = XDocument.Parse(xcontent);
xdoc.Save("FullFileName.xml");

2。方法:

XmlReader rdr = XmlReader.Create(new StringReader(xcontent));
XDocument xdoc = XDocument.Load(rdr);
xdoc.Save("FullFileName.xml");

返回:

<Person xmlns="http://someURI.com/something">
  <FirstName>Name1</FirstName>
  <MiddleName>Name2</MiddleName>
  <LastName>Name3</LastName>
</Person>

Msdn 文档:https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument%28v=vs.110%29.aspx

【讨论】:

    【解决方案2】:

    也可以逐行读写。

                string line = string.Empty;
                using (StreamReader file_r = new System.IO.StreamReader("HasBlankLines.xml"))
                {
                    using (StreamWriter file_w = new System.IO.StreamWriter("NoBlankLines.xml"))
                    {
                        while ((line = file_r.ReadLine()) != null)
                        {
                            if (line.Trim().Length > 0)
                                file_w.WriteLine(line);
                        }
                    }
                }
    

    输出:

    <Person xmlns="http://someURI.com/something">
        <FirstName>Name1</FirstName>
        <MiddleName>Name2</MiddleName>
        <LastName>Name3</LastName>
    </Person>
    

    【讨论】:

    • 这假定所有元素的值都不是故意包含空行的文本节点。
    猜你喜欢
    • 2016-11-05
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多