Antoni Nicyfor Antoni Nicyfor - 1 year ago 93
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">
<rowset name="typeids" key="typeID" columns="typeName,TypeID">
<row typeName="Construction Blocks" typeID="3828" />

Currently I am trying to get the value of the
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)

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

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

Answer Source

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`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download