dlarkin77
dlarkin77

Reputation: 879

Selecting attribute values into a List<string>

Given the following XML, I need to be able to get the name of the users in the Household_Services category.

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <category id="Household_Services">
    <users>
      <add name="ESB"/>
      <add name="BordGais"/>
      <add name="Eircom"/>
    </users>
  </category>
  <category id="Financial_Accounts">
    <users>
      <add name="BankOfIreland"/>
      <add name="AIB"/>
    </users>
  </category>
  <category id="Health_Records">
    <users>
      <add name="VHI"/>
      <add name="IrishLife"/>
    </users>
  </category>
</root>

The closest I can get is

string category = "Household_Services";

var users = from n in xe.Elements("category")
            where (string)n.Attribute("id") == category
            select n.Element("users").Elements("add").Attributes("name");

This gives me an IEnumerable<XAttribute> but what I need is a List<string>.

Any ideas what I need to change?

Thanks,

David

Upvotes: 1

Views: 1672

Answers (2)

Zebi
Zebi

Reputation: 8882

You have to access the Value Property of your XAttribute.

either

var attributes = from n in xe.Elements("category")
        where (string)n.Attribute("id") == category
        from attribute in n.Element("users").Elements("add").Attributes("name")
        select attribute.Value
var users = attributes.Select(x => x.Value);

or

var users = from n in xe.Elements("category")
        where (string)n.Attribute("id") == category
        from attribute in n.Element("users").Elements("add").Attributes("name")
        select attribute.Value

would to the trick.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190941

change this line

select n.Element("users").Elements("add").Attributes("name");

to

select n.Element("users").Elements("add").Attributes("name").Select(a => a.ToString()).ToList();

Upvotes: 2

Related Questions