简体   繁体   English

使用LINQ选择多个XML节点属性。为什么第一个属性之后的所有内容都为null?

[英]Selecting multiple XML node attributes with LINQ.. why is everything after the first attribute null?

I have the following sample XML: 我有以下示例XML:

<?xml version="1.0" encoding="utf-8" ?>
<queryableData>
  <table displayName="Shipments" dbName="Quotes">
    <foreignKey column="CustomerId" references="CustomerRegistration"/>
    <foreignKey column="QuoteStatusId" references="QuoteStatus"/>
    <fields>
      <field displayName="Quote Charge" dbColumn="QuoteCharge" type="Number"/>
      <field displayName="Total Weight" dbColumn="TotalWeight" type="Number"/>
    </fields>
  </table>
</queryableData>

and I'm trying to create an anonymous object with the contents of the field node. 并且我正在尝试使用field节点的内容创建一个匿名对象。 Here is my LINQ code: 这是我的LINQ代码:

XElement root = XElement.Load("queryable.xml");
var elem = from el in root.Elements("table")
select new
{
    DisplayName = el.Attribute("displayName").Value,
    Column = el.Attribute("dbColumn").Value,
    DataType = el.Attribute("type").Value
};

If I only specify the "DisplayName" attribute, it works fine. 如果我仅指定“ DisplayName”属性,则可以正常工作。 The other two are always null, and therefore trying to read the Value property is throwing a NullReferenceException. 其他两个始终为null,因此尝试读取Value属性将引发NullReferenceException。

What's the correct way to grab all of the three attributes that I need from the element? 从元素中获取我需要的所有三个属性的正确方法是什么? I think I am on the right track but missing something with the query (it seems to me that el isn't the entire element) 我认为我走了正确的路,但是查询中缺少了一些东西(在我看来, el并不是整个元素)

EDIT: Nevermind, I'm an idiot. 编辑:没关系,我是个白痴。 I'm looking at one element and querying for the other! 我正在寻找一个元素,并查询另一个!

In your sample document the sole table element has two attributes named displayName and dbName , I don't see any dbColumn or type attribute on the table element. 在示例文档中,唯一的table元素具有两个名为displayNamedbName属性,我在该table元素dbColumn不到任何dbColumntype属性。 If you want to access the field elements then use root.Descendants("field") instead of root.Element("table") . 如果要访问field元素,请使用root.Descendants("field")代替root.Element("table")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM