使用 LINQ 选择多个 XML 节点属性..为什么第一个属性之后的所有内容都是 null?
我有以下示例 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>
并且我正在尝试使用 field
节点的内容创建一个匿名对象。这是我的 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
};
如果我只指定“DisplayName”属性,它就可以正常工作。另外两个始终为 null,因此尝试读取 Value 属性会引发 NullReferenceException。
从元素中获取我需要的所有三个属性的正确方法是什么?我认为我走在正确的轨道上,但在查询中遗漏了一些东西(在我看来, el 不是整个元素)
编辑:没关系,我是个白痴。我正在查看一个元素并查询另一个元素!
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="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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的示例文档中,唯一的
table
元素有两个名为displayName
和dbName
的属性,我没有看到任何dbColumn
> 或table
元素上的type
属性。如果您想访问field
元素,请使用root.Descendants("field")
而不是root.Element("table")
。In your sample document the sole
table
element has two attributes nameddisplayName
anddbName
, I don't see anydbColumn
ortype
attribute on thetable
element. If you want to access thefield
elements then useroot.Descendants("field")
instead ofroot.Element("table")
.