【问题标题】:get attribute value from multiple elements with same name and attribute value of one other element in xml从xml中具有相同名称和另一个元素的属性值的多个元素中获取属性值
【发布时间】:2025-11-23 16:25:01
【问题描述】:

我有一个如下所示的 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。

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:
    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 元素上为List&lt;string&gt; 提供href 属性的值。

    【讨论】:

      最近更新 更多