开发者

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

I have the following sample XML:

<?xml version="1.0" encoding="utf-8" ?>
<queryableData>
  <table displayName="Shipments" dbName="Quotes">
    <foreignKey column="CustomerId" references="CustomerRegistration"/>
    <foreignKey column="开发者_StackOverflow中文版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. Here is my LINQ code:

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. The other two are always null, and therefore trying to read the Value property is throwing a 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)

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. If you want to access the field elements then use root.Descendants("field") instead of root.Element("table").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜