Antoni Nicyfor Antoni Nicyfor - 13 days ago 5
C# Question

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>


Currently I am trying to get the value of the
typeID
attribute from this xml using this code:

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));
}


However the
foreach
statement never fires. What am I doing wrong here?

Edit: Sorry, I put in the wrong xml. Correct xml is now there

Answer

First of all you should use .Descendants() and not 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`