2016-11-24 69 views
1
<?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属性的值:如何获得使用linq到xml的属性的值?

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是现在有

回答

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` 
0

在你的XML,没有typeName取名为Construction Blocks,所以结果会很明显ly null。

所以foreach循环没有任何集合。