<?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
答案 0 :(得分:1)
首先,您应该使用.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`
答案 1 :(得分:0)
在您的xml中,没有名为 typeName
的 Construction Blocks
,因此结果显然为null。
所以foreach循环没有任何集合。