我想从一个XML文件中选择属于单个父元素的5个元素值。
我遵循了几个“选择所有元素...”的例子。或者“获取单个父级下的元素...”他们没有回答这个问题。至少在某种程度上我可以应用相同的解决方案。
{
var xdoc = XElement.Load(FileName);
List<string> locations = new List<string>();
locations = xdoc.Elements("Locations")
.Where(x => x.Attribute("ID").Value == lab)
.SelectMany(e => e.Elements("Location").Select(n => n.Attribute("ID").Value)).ToList();
foreach (string id in locations)
{
locID += id + "," ;
}
locID.TrimEnd(',');
}
XML文件的一部分
<Locations ID="North America">
<Location ID="23023" />
<Location ID="23024" />
<Location ID="20323" />
<Location ID="22483" />
</Locations>
西班牙和南美还有其他类似的区块。
我想要一个逗号分隔的位置I字符串,但是位置列表有count=0。我只是不能让我的选择正确。
发布于 2019-06-04 02:49:04
如果有多个Locations元素,您可以尝试这样做:
doc.Root.Elements("Locations").Elements("Location").Select(x=>x.Attribute("ID").Value)
var csv = string.Join(',', ids);
如果您只是寻找ID,则不需要.SelectMany()
https://stackoverflow.com/questions/56432752
复制相似问题