2016-11-24 4 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> 

В настоящее время я пытаюсь получить значение атрибута typeID из этого XML, используя этот код:Как получить значение атрибута с помощью 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. не Correct 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, нет typeNameConstruction Blocks, поэтому результат будет очевиден ly null.

Так что для петли foreach нет никакой коллекции.