简体   繁体   English

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

[英]get attribute value from multiple elements with same name and attribute value of one other element in xml

I have got a xml file which looks like this: 我有一个xml文件,如下所示:

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

I am trying to select a pair of information from these nodes: the event id (12345) and the attribute of the elements option 我试图从这些节点中选择一对信息:事件id(12345)和elements选项的属性

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

unfortunately this produces the following for options inside my foreach-loop: item.options = "System.Xml.Linq.Extensions+d__8" 不幸的是,这为我的foreach循环中的选项产生了以下内容:item.options =“System.Xml.Linq.Extensions + d__8”

What I want is: 12345, 1234 (yes I do not mind if the attribute value of the 4 option elements are in one string. And I also cannot change the xml file and I would prefer to use only linq. 我想要的是:12345,1234(是的我不介意4个选项元素的属性值是否在一个字符串中。而且我也无法更改xml文件,我宁愿只使用linq。

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

This will you List<string> with values of href attribute on option elements under given event element. 这将使用给定event元素下的option元素的List<string> href属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM