简体   繁体   中英

XML Return parent node when searching children

I have the following XML

<Log>
<Log>
    <Log>
    </Log>
    <Log>
        <Guid>16fea409-58cc-e211-9b7f-005056b00085</Guid>
    </Log>
</Log>
<Log>
    <Log>
    </Log>
    <Log>
        <Guid>16fea409-58cc-e211-9b7f-005056b00086</Guid>
    </Log>
</Log>
<Log>
    <Log>
    </Log>
    <Log>
        <Guid>16fea409-58cc-e211-9b7f-005056b00087</Guid>
    </Log>
</Log>
</Log>

I would like to return the 2nd element Log and below when searching for Guid, eg

<Log>
    <Log>
    </Log>
    <Log>
        <Guid>16fea409-58cc-e211-9b7f-005056b00085</Guid>
    </Log>
</Log>

I've tried all sorts using linq to xml but can't seem to get it right, can anyone help?

    XElement Log = XElement.Parse(responseXml)
    .Elements("Log")
    .Where(x => x.Element("Guid").Value == "16fea409-58cc-e211-9b7f-005056b00085")
    .FirstOrDefault();

You can do this with Linq and XPath (add reference to System.Xml.XPath namespace):

var guid = "16fea409-58cc-e211-9b7f-005056b00086";
var log = xdoc.XPathSelectElements("//Log[Log/Guid]")
              .Where(g => (string)g.XPathSelectElement("Log/Guid") == guid)
              .FirstOrDefault();

Expression //Log[Log/Guid] selects all Log elements, which have at least one Log child with inner Guid element. Code above returns:

<Log>
  <Log></Log>
  <Log>
    <Guid>16fea409-58cc-e211-9b7f-005056b00086</Guid>
  </Log>
</Log>

Or with simple Linq. You can use Parent property. But in this case you need to be sure, that all Guid elements are nested only within at least two Log elements

var guid = "16fea409-58cc-e211-9b7f-005056b00086";
var log = xdoc.Descendants("Guid")
              .Where(g => (string) g == guid)
              .Select(g => g.Parent.Parent)
              .FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM