2012-12-05 28 views
10

我有一個XML文件,它看起來像這樣不同的屬性如何刪除從XML元素:使用的XDocument,當我們有多個同名的元素,但

<Applications> 
    <myApp> 
    <add key="ErrorDestinationEventLog" value="EventLog" /> 
    <add key="version" value="5.0.0.0" /> 
    <add key="DebugMode_RUN" value="true" /> 
    </myApp> 
</Applications> 

所有元素都具有相同的元素名稱但不同屬性。 如何在C#中使用XDocument從一個xml中移除一個特定元素?

xd.Element("Applications").Element("myApp").Element(xe.Name).RemoveAll(); 

上述命令不起作用,因爲所有元素都具有相同的名稱。

是否有任何方法來識別一個元素,而不是它的名字? 如果是這樣,我該如何使用它從XDocument中刪除它?

+0

您是否調試過代碼?你知道什麼.Element(「myApp」)正在返回嗎?只需要尋找更多有關你所看到的事情的信息。 – Jr0

+0

感謝您的建議。我明白.Element(「myApp」)返回名稱爲「myApp」的第一個元素,對嗎? –

回答

15
string key = "version"; 
XDocument xdoc = XDocument.Load(path_to_xml); 
xdoc.Descendants("add") 
    .Where(x => (string)x.Attribute("key") == key) 
    .Remove(); 

UPDATE你幾乎做了工作。你錯過的是按屬性值過濾元素。這裏是你的代碼過濾和刪除選定的元素:

xd.Element("Applications") 
    .Element("myApp") 
    .Elements("add") 
    .Where(x => (string)x.Attribute("key") == key) 
    .Remove(); 
2
xd.Descendants("add") 
    .First(a => a.Attribute("key").Value == "version") 
    .Remove(); 

如果你有一個包含addApplications下比myApp其它標籤,你可能更喜歡一個更安全的版本

xd.Descendants("myApp").First() 
    .Descendants("add") 
    .Where(x => (string)x.Attribute("key") == "version") 
    .Remove(); 

你也可以使用XPath(System.Xml.XPath)

string key="version"; 
xd.XPathSelectElement(String.Format("//myApp/add[@key='{0}']",key)).Remove(); 
+1

感謝您的回覆。我的xml確實有其他標籤包含「添加」。 –

相關問題