我有一个包含元素子元素的XML文件:
<Root>
<Location>
<DepartureBoundary>
<DepartureBoundaryRadius>600</DepartureBoundaryRadius>
</DepartureBoundary>
</Location>
<Location>
<DepartureBoundary>
<DepartureBoundaryRadius>600</DepartureBoundaryRadius>
</DepartureBoundary>
</Location>
</Root>
目前,我正在执行以下操作来访问DepartureBoundaryRadius的值:
XDocument locationsDoc = XDocument.Load("file.xml");
DepartureLocationBoundaryRadius = null;
List<DepartureBoundaryRadius> radiusList = new List<DepartureBoundaryRadius>();
foreach (XElement locationElement in locationsDoc.Descendants("Root"))
{
foreach (XElement locationSubElement in locationsDoc.Descendants("Location"))
{
foreach (XElement departureElement in locationsDoc.Descendants("DepartureBoundary"))
{
DepartureLocationBoundaryRadius = departureElement.Element("DepartureRadius").Value));
radiusList.Add(DepartureLocationBoundaryRadius);
}
}
}
有更简单的方法吗?我宁愿在一行或一个语句中分配DepartureLocationBoundaryRadius的值 - 特别是因为每个Location只有一个DepartureBoundaryRadius值。有什么想法吗?谢谢!
答案 0 :(得分:0)
我认为你的意思是Elements
。 Descendants
已经提供了您想要的内容
var values = locationsDoc.Descendants("DepartureBoundaryRadius")
.Select(x => x.Value)
.ToList();
答案 1 :(得分:0)
var list = xdoc.Document.Descendants("DepartureBoundaryRadius").Select(x=>x.Value);