我正在尝试从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();
关于找出为什么我没有得到我期望的结果的任何帮助,将不胜感激。
如果节点缺少属性,可能会发生这种情况。试试:
var bar = doc.Descendants("node")
.Where(x => (string)x.Attribute("type") == "type1")
.ToList();
var bar = doc.Descendants("node")
.Where(x => x.Attribute("type") != null && x.Attribute("type").Value == "type1")
.ToList();
为空值添加保护措施可以解决您的问题。
var bar = doc.Descendants() //Checking all the nodes, not just the "node"
.Where(x => x.Attribute("type")?.Value == "type1")//if the attribute "type" is not null, check the Value == "type1",
.ToList();//immediately executes the query and returns a List<XElement> by the value of attribute "type"
这是一个选项,如果您需要检查文档/元素的所有节点中特定属性的值。