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

3
我有一个看起来像这样的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 = "System.Xml.Linq.Extensions+d__8"。

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

1个回答

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(),
                      };

这将使用给定的event元素下option元素上的href属性值列出List<string>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接