我试图从XElement (使用.Remove())删除后代元素,我似乎得到一个空对象引用,我不知道为什么。根据属性值从XML中删除元素?
说完看着前面的问题与这个称号(see here),我找到了一种方法来删除它,但我仍然不明白为什么我第一次尝试没有工作的方式。
有人能够启发我吗?
String xml = "<things>"
+ "<type t='a'>"
+ "<thing id='100'/>"
+ "<thing id='200'/>"
+ "<thing id='300'/>"
+ "</type>"
+ "</things>";
XElement bob = XElement.Parse(xml);
// this doesn't work...
var qry = from element in bob.Descendants()
where element.Attribute("id").Value == "200"
select element;
if (qry.Count() > 0)
qry.First().Remove();
// ...but this does
bob.XPathSelectElement("//thing[@id = '200']").Remove();
感谢, 罗斯
谢谢svick,我明白了现在的问题。 – 2012-01-16 10:26:17