2

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ノードを見つけて、要素があるかどうかを確認しています。

4

2 に答える 2

1

少し変更して、Alex Filipovici の回答をコピーしただけです。

var xDoc = XDocument.Load("input.xml");
    xDoc.Descendants()
        .Where(d => d.Name.LocalName == "line_item" && !d.HasElements)
        .ToList()
        .ForEach(e => e.Remove());
于 2013-10-30T11:53:46.420 に答える
0

これを試して:

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());
于 2013-10-30T11:51:04.157 に答える