开发者

Linq XML query - How do I return a node that meets a condition within its own nested nodes?

开发者 https://www.devze.com 2023-02-17 08:00 出处:网络
I have the following xml structure: <?xml version=\"1.0\" encoding=\"utf-8\" ?> <administrators>

I have the following xml structure:

<?xml version="1.0" encoding="utf-8" ?>
<administrators>
   <administrat开发者_JS百科or>
    <fullname>full name1</fullname>
    <email>email1@email.com</email>
    <provinces>
      <province>3</province>
      <province>9</province>
    </provinces>
  </administrator>
  <administrator>
    <fullname>full name2</fullname>
    <email>email2@email.com</email>
    <provinces>
      <province>1</province>
      <province>2</province>
    </provinces>
  </administrator>
</administrators>

I want to be able to return administrator nodes that have particular province nodes. I have tried the following:

IEnumerable<Administrator> admins = RootElement.Elements("administrator")
        .Where(x => x.Elements("provinces")
                .Any(p => int.Parse(p.Element("province").Value) == provinceId))
        .Select(x => new Administrator()
        {
            FullName = x.Element("fullname").Value,
            Email = x.Element("email").Value
        });

and my result set is empty.

So what am I missing here? if provinceId = 3 how do I select the administrator element that has a province element that equals provinceId?


This is a good case for using XPath:

  RootElement.XPathSelectElements("//administrator[provinces/province = '" + provinceId + "']");


    var admins = RootElement.Elements("administrator")
.Where( a => a.Descendants("province").Any( p => int.Parse(p.Value) == provinceId ) );


IEnumerable<Administrator> admins = RootElement.Elements("administrator")
    .Where(x => x.Elements("provinces")
            .SelectMany(p => p.Elements("province"))
            .Any(p => int.Parse(p.Value) == provinceId))
    .Select(x => new Administrator()
    {
        FullName = x.Element("fullname").Value,
        Email = x.Element("email").Value
    });

(I have not yet tested this.)

0

精彩评论

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