我试图从 XElement (使用 .Remove()) 中移除一个后代元素,但我似乎得到了一个空对象引用,我不确定为什么。
查看了上一个标题为 ( 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();
谢谢, 罗斯
请您参考如下方法:
问题是您正在迭代的集合包含一些没有 id 属性的元素。对于他们来说,element.Attribute("id") 是 null,因此尝试访问 Value 属性会抛出一个 NullReferenceException.
解决这个问题的一种方法是使用 a cast而不是 Value:
var qry = from element in bob.Descendants()
where (string)element.Attribute("id") == "200"
select element;
如果一个元素没有 id 属性,转换将返回 null,这在这里工作正常。
如果您要进行转换,也可以转换为 int?,如果您愿意的话。
