从xml中具有相同名称和另一个元素的属性值的多个元素中获取属性值

时间:2015-03-15 01:06:15

标签: c# xml linq

我有一个xml文件,如下所示:

<events>
    <event id="12345">
        <option href="1"></option>
        <option href="2"></option>
        <option href="3"></option>
        <option href="4"></option>
    </event>
</events>

我正在尝试从这些节点中选择一对信息:事件ID(12345)和元素选项的属性

var nodeWithOptions = from n in xml.Descendants("event")
                      select new
                      {
                           id = n.Attribute("id").Value,
                           options = n.Elements("option").Attributes("href").ToString(),
                      };

不幸的是,这会为我的foreach循环中的选项产生以下内容:item.options =&#34; System.Xml.Linq.Extensions + d__8&#34;

我想要的是:12345,1234(是的,我不介意4个选项元素的属性值是否在一个字符串中。而且我也无法更改xml文件,我宁愿只使用linq。

1 个答案:

答案 0 :(得分:2)

var nodeWithOptions = from n in xml.Descendants("event")
                      select new
                      {
                           id = (string)n.Attribute("id"),
                           options = n.Elements("option")
                                      .Select(x => (string)x.Attribute("href"))
                                      .ToList(),
                      };

对于List<string>元素下的href元素,您option的{​​{1}}属性值为event

相关问题