我有一个如下所示的 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。
最佳答案
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
上的属性给定元素 event
元素。
关于c# - 从具有相同名称的多个元素和 xml 中另一个元素的属性值获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056121/