XDocument后代的后代简单陈述

时间:2015-07-28 21:50:48

标签: c# .net-3.5 linq-to-xml

我有一个包含元素子元素的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值。有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

我认为你的意思是ElementsDescendants已经提供了您想要的内容

var values = locationsDoc.Descendants("DepartureBoundaryRadius")
                          .Select(x => x.Value)
                          .ToList();

答案 1 :(得分:0)

 var list = xdoc.Document.Descendants("DepartureBoundaryRadius").Select(x=>x.Value);