简体   繁体   English

从XDocument C#中删除第n个xelement

[英]Delete nth xelement from xdocument c#

I have xml like below. 我有下面的XML。 I want to delete nth product node from that xml. 我想从该xml中删除第n个产品节点。

I had tried this but not working. 我已经尝试过了,但是没有用。

document.Descendants("products").Descendants("product").Take(1)

XML XML格式

<products>
    <product>
        <territory>A</territory>
    </product>
    <product>
        <territory>B</territory>
    </product>
    <product>
        <territory>C</territory>
    </product>
    <product>
        <territory>D</territory>
    </product>
    <product>
        <territory>E</territory>
    </product>
</products>

How to delete 3rd product node from this xml? 如何从此xml中删除第三个产品节点?

You can't access child nodes by using an index. 您无法使用索引访问子节点。 One way would be: 一种方法是:

document.Descendants("products").Descendants("product").Skip(2).Take(1);

I suggest using Linq to Xml . 我建议对Xml使用Linq You could use ElementAt and find an element at a given position, one could call Remove on a find element to remove the element. 您可以使用ElementAt在给定位置查找元素,可以在find元素上调用Remove来删除该元素。

    int position = 3;  // Specify position.
    XElement element = XElement.Parse(input);

    element                                      
        .Elements("product")
        .ElementAt(3)
        .Remove();

Ouput 乌普特

 <products>
  <product>
    <territory>A</territory>
  </product>
  <product>
    <territory>B</territory>
  </product>
  <product>
    <territory>C</territory>
  </product>
  <product>
    <territory>E</territory>
  </product>
</products>

Check this Demo 检查这个Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM