我得到的代码看起来像这样。

    public void Delete(Feed item)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("Feed.xml");
        XmlNodeList nodes = doc.SelectNodes("/Feeds/Input");
        foreach (XmlNode noden in nodes)
        {
            if (noden.SelectSingleNode("Id").InnerText == item.Id.ToString())
            {
                nodes[iterator].RemoveAll();
                noden.RemoveAll();

                break;
            }
        }
        doc.Save("Feed.xml");
    }


这是我的xml的示例

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Feeds>
  <Input>
    <Name>Examplename</Name>
    <Id>572b9c08-0d76-415d-9b53-ac2e87fceae6</Id>
    <Url>Examppleurl</Url>
    <Category>Logic.Entities.Category</Category>
    <Feed>
      <Id>ExampleID</Id>
      <Title>12. A strange week to be Swedish</Title>
      <Enclosure>example.mp3</Enclosure>
    </Feed>
    <Feed>
      <Id>anotherexampleid</Id>
      <Title>11. The not-Malala-guy</Title>
      <Enclosure>another example.mp3</Enclosure>
    </Feed>
  </Input>
  <Input>
<Feeds>
  <Input>
    <Name>Examplename</Name>
    <Id>572b9c08-0d76-415d-9b53-ac2e87fceae6</Id>
    <Url>Examppleurl</Url>
    <Category>Logic.Entities.Category</Category>
    <Feed>
      <Id>ExampleID</Id>
      <Title>12. A strange week to be Swedish</Title>
      <Enclosure>example.mp3</Enclosure>
    </Feed>
    <Feed>
      <Id>anotherexampleid</Id>
      <Title>11. The not-Malala-guy</Title>
      <Enclosure>another example.mp3</Enclosure>
    </Feed>
  </Input>
  </Input>
</Feeds>


当我像上面的代码一样删除它时,它会删除我想要的那个,但留空

<input>
</input>


所以我的问题是我想删除空输入...我将如何进行呢?

谢谢。

最佳答案

您只能使用更特定的XPath选择要删除的<Input>节点:

string xpath = String.Format("/Feeds/Input[Id='{0}']", item.Id.ToString());
XmlNodeList nodes = doc.SelectNodes(xpath);


然后像这样删除它们:

foreach (XmlNode noden in nodes)
{
    noden.ParentNode.RemoveChild(noden);
}

关于c# - 从XmlDocument中删除子节点并包括该元素的父节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26586663/

10-14 16:57
查看更多