2014-10-27 63 views
2

我得到的代碼如下所示。從XmlDocument中刪除子節點幷包含元素的父節點

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> 

所以我的問題是我想刪除空的輸入...我會繼續嗎?

謝謝。

+0

這XML看起來是錯誤的。 'Feeds'是否有'Input'元素?到最後,你有一個'Input'元素,它包含'Feeds'。如果你格式化XML,我想你會明白我的意思。 – Yuck 2014-10-27 11:53:15

+0

對不起,這裏的代碼格式有點難以理解。 它看起來像這樣一旦我刪除了兩個輸入。 <?XML版本= 「1.0」 編碼= 「UTF-8」 獨立= 「是」?> que 2014-10-27 11:59:21

+0

請編輯您的帖子修復XML。 – 2014-10-27 14:47:07

回答

0

您可以選擇使用更具體的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); 
} 
+0

這就是它!謝謝,不知道你可以像這樣指定xpath。 – que 2014-10-27 12:17:37

相關問題