删除没有子体的 XML 节点

本文关键字:XML 节点 删除 | 更新日期: 2023-09-27 18:37:23

我有一个XML文件。我想删除没有任何后代的line_item节点。

<root>
  <transaction>
    <type>regular</type>
    <number>746576</number>
    <customer>
      <mobile>5771070</mobile>
      <email />
      <name>abcd</name>
    </customer>
    <line_items>
      <line_item>
        <serial>8538</serial>
        <amount>220</amount>
        <description>Veggie </description>
        <qty>1</qty>
        <attributes />
      </line_item>
      <line_item />
      <line_item />
      <line_item />
      <line_item />
      <line_item>
        <serial>8543</serial>
        <description>Tax</description>
        <qty>1</qty>
        <value>42.78</value>
        <attributes />
      </line_item>
    </line_items>
    <associate_details>
      <code>660</code>
      <name>xyz</name>
    </associate_details>
  </transaction>
</root>

我正在使用 ASP.NET 4。现在我正在找到line_item节点并检查它是否有元素。

删除没有子体的 XML 节点

只是复制了Alex Filipovici的答案,做了一些修改:

var xDoc = XDocument.Load("input.xml");
    xDoc.Descendants()
        .Where(d => d.Name.LocalName == "line_item" && !d.HasElements)
        .ToList()
        .ForEach(e => e.Remove());

试试这个:

using System.Linq;
using System.Xml.Linq;
class Program
{
    static void Main(string[] args)
    {
        var xDoc = XDocument.Load("input.xml");
        xDoc.Descendants()
            .Where(d => 
                d.Name.LocalName == "line_item" && 
                d.Elements().Count() == 0)
            .ToList()
            .ForEach(e => e.Remove());
        // TODO: 
        //xDoc.Save(savePath);
    }
}

更短(且更快)的替代方法是使用以下语法:

xDoc.Descendants("line_item")
    .Where(d => !d.HasElements)
    .ToList()
    .ForEach(e => e.Remove());