2016-11-24 83 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循環沒有任何集合。