【问题标题】:LINQ to XML - Trying to select a list of elements by the value of their attributesLINQ to XML - 尝试按属性值选择元素列表
【发布时间】: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&lt;XElement&gt;,其中包含 type="type1" 的两个节点,例如

  <node type="type1">some text</node>
  <node type="type1">some more text</node>

我正在使用 var doc = XDocument.Load(@"C:\document.xml"); 加载文档

我可以得到一个IEnumerable&lt;XAttribute&gt;,其中包含我想要使用的节点的属性

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


    【解决方案1】:

    如果节点缺少该属性,则可能会发生这种情况。试试:

     var bar = doc.Descendants("node")
        .Where(x => (string)x.Attribute("type") == "type1")
        .ToList();
    

    【讨论】:

      【解决方案2】:
      var bar = doc.Descendants("node")
      .Where(x => x.Attribute("type") != null && x.Attribute("type").Value == "type1")
      .ToList();
      

      为空值添加保护可以解决您的问题。

      【讨论】:

        【解决方案3】:
        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"
        

        这是一个选项,如果您需要检查文档/元素的所有节点中特定属性的值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-06-10
          • 1970-01-01
          • 2023-03-06
          • 1970-01-01
          • 1970-01-01
          • 2012-09-24
          • 1970-01-01
          相关资源
          最近更新 更多