如何使用 linq to xml 获取属性的值?
How do I get the value of an attribute using linq to xml?
<?xml version='1.0' encoding='UTF-8'?>
<eveapi version="2">
<result>
<rowset name="typeids" key="typeID" columns="typeName,TypeID">
<row typeName="Construction Blocks" typeID="3828" />
</rowset>
</result>
</eveapi>
目前我正在尝试使用此代码从此 xml 获取 typeID
属性的值:
var result = from el in doc.Elements("row")
where (string)el.Attribute("typeName") == "Construction Blocks"
select el.Attribute("typeID").Value;
foreach (string el in result)
{
typeID.Add(Convert.ToInt32(el));
}
但是 foreach
语句永远不会触发。我在这里做错了什么?
编辑:对不起,我输入错误xml。正确的 xml 现在在那里
首先你应该使用 .Descendants()
而不是 Elements
:
var result = (from el in doc.Descendants("row")
where (string)el.Attribute("typeName") == "Construction Blocks"
select Convert.ToInt32(el.Attribute("typeID").Value)).ToList();
// See that you can just perform the `Convert` in the `select` instead of having a
// `foreach`. If you need to put the results into an initialized list then you can remove
// the `ToList()` and just have an `AddRange` on your list to the `result`
- 要了解区别,请参阅:有什么区别
在 Linq to XML Descendants 和 Elements
之间
在您的 xml 中,没有名为 Construction Blocks
的 typeName
,因此结果显然为空。
所以foreach循环没有任何集合。
<?xml version='1.0' encoding='UTF-8'?>
<eveapi version="2">
<result>
<rowset name="typeids" key="typeID" columns="typeName,TypeID">
<row typeName="Construction Blocks" typeID="3828" />
</rowset>
</result>
</eveapi>
目前我正在尝试使用此代码从此 xml 获取 typeID
属性的值:
var result = from el in doc.Elements("row")
where (string)el.Attribute("typeName") == "Construction Blocks"
select el.Attribute("typeID").Value;
foreach (string el in result)
{
typeID.Add(Convert.ToInt32(el));
}
但是 foreach
语句永远不会触发。我在这里做错了什么?
编辑:对不起,我输入错误xml。正确的 xml 现在在那里
首先你应该使用 .Descendants()
而不是 Elements
:
var result = (from el in doc.Descendants("row")
where (string)el.Attribute("typeName") == "Construction Blocks"
select Convert.ToInt32(el.Attribute("typeID").Value)).ToList();
// See that you can just perform the `Convert` in the `select` instead of having a
// `foreach`. If you need to put the results into an initialized list then you can remove
// the `ToList()` and just have an `AddRange` on your list to the `result`
- 要了解区别,请参阅:有什么区别 在 Linq to XML Descendants 和 Elements 之间
在您的 xml 中,没有名为 Construction Blocks
的 typeName
,因此结果显然为空。
所以foreach循环没有任何集合。