选择属性值为List <string> </string>

时间:2011-03-19 18:07:53

标签: c# linq-to-xml

鉴于以下XML,我需要能够获取Household_Services类别中用户的名称。

<?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>

我能得到的最接近的是

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

这给了我IEnumerable<XAttribute>但我需要的是List<string>

我需要改变什么想法?

谢谢,

大卫

2 个答案:

答案 0 :(得分:2)

更改此行

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

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

答案 1 :(得分:1)

您必须访问XAttribute的Value属性。

或者

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

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

会成功。