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 (str开发者_如何学运维ing)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
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();
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.
精彩评论