开发者

C#, LINQ Getting Child elements of a Specified Parent Element

I hope that makes sense. I have the following XML document.

<PrinterDirectory>
  <Country Name="UK>
    <Region Name="Aberdeen" />
    <Region Name="Birmingham" />
    <Region Name="London" />
  </开发者_开发知识库Country>
  <Country Name="France">
    <Region Name="Paris" />
    <Region Name="Bordeaux" />
  </Country>
</PrinterDirectory>

What is the LINQ to retrieve just the regions of UK for example?

I've tried

varRegionQuery = from items in xdoc.Descendants("Country")
                 where items.Attribute("Name").Value == "UK"
                 select new
                 {
                    _Region = items.Element("Region").Attribute("Name").Value
                 };

That however only retrieves "Aberdeen".


The simplest way is probably to use a subsequent from clause, like this:

var regionQuery = from items in xdoc.Descendants("Country")
                  where items.Attribute("Name").Value == "UK"
                  from region in items.Elements("Region")
                  select region.Attribute("Name").Value;

Note that that will cope with multiple <Country Name="UK"> elements.


var regionQuery = from item in xdoc.Descendants("Country")
                              let countryCode = item.Attribute("Name") ?? new XAttribute("Name", string.Empty)
                              where countryCode.Value == "UK"
                              from region in item.Descendants("Region")
                              let regionName = region.Attribute("Name") ?? new XAttribute("Name", string.Empty)
                              select new {Name = regionName};

Let statements are handy in case you have a null value in your xml. This lets us gather all the data even if some of it is invalid and then we can deal with getting the junk out later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜