【发布时间】:2010-11-11 21:25:08
【问题描述】:
我正在尝试从节点具有特定属性值的 XML 文档中获取元素列表。文档的结构如下:
<root>
<node type="type1">some text</node>
<node type="type2">some other text</node>
<node type="type1">some more text</node>
<node type="type2">even more text</node>
</root>
我想要的结果是一个IEnumerable<XElement>,其中包含 type="type1" 的两个节点,例如
<node type="type1">some text</node>
<node type="type1">some more text</node>
我正在使用 var doc = XDocument.Load(@"C:\document.xml"); 加载文档
我可以得到一个IEnumerable<XAttribute>,其中包含我想要使用的节点的属性
var foo = doc.Descendants("node")
.Attributes("type")
.Where(x => x.Value == "type1")
.ToList();
但是,如果我尝试使用下面的代码获取包含这些属性的元素,则会收到 Object reference not set to an instance of an object. 错误。我使用的代码是
var bar = doc.Descendants("node")
.Where(x => x.Attribute("type").Value == "type1")
.ToList();
任何有关找出我没有得到预期结果的原因的帮助将不胜感激。
【问题讨论】:
标签: c# xml linq linq-to-xml