Search code examples
c#xmlxdoc

Using xdoc to find multiple sub descendant elements within a specific top elements


I have this type of xml file and I am trying to get the Id and Host for each group.

<AAA>
  <Group>BTeam</Group>
  <CCC>
    <DDD>
      <Id>1234</Id>
      <Host>BTeamHost</Host>
    </DDD>
  </CCC>
</AAA>

<AAA>
  <Group>CTeam</Group>
  <CCC>
    <DDD>
      <Id>3234</Id>
      <Host>CTeamHost</Host>
    </DDD>
  </CCC>
</AAA>  

Currently i am able to get each group in the file, but the code below can't match on the group.Value

XDocument xdoc = XDocument.Load(xml);
foreach (XElement group in xdoc.Root.Descendants("AAA").Elements("Group"))
{
    if (xdoc.Root.Descendants("AAA").Elements("Group").Equals(group.Value))
    {
        var id = xdoc.Root.Descendants("AAA").Descendants("CCC").Descendants("DDD").Descendants("Id").FirstOrDefault().Value;
        var host = xdoc.Root.Descendants("AAA").Descendants("CCC").Descendants("DDD").Descendants("Host").FirstOrDefault().Value;
        Console.WriteLine("Group: {0} Id: {1} Host: {2}", group, id, host);
    }
}

If i just try this, i get the same id and host from the first Group, instead of from each group.

XDocument xdoc = XDocument.Load(xml);
foreach (XElement group in xdoc.Root.Descendants("AAA").Elements("Group"))
{
    var id = xdoc.Root.Descendants("AAA").Descendants("CCC").Descendants("DDD").Descendants("Id").FirstOrDefault().Value;
    var host = xdoc.Root.Descendants("AAA").Descendants("CCC").Descendants("DDD").Descendants("Host").FirstOrDefault().Value;
    Console.WriteLine("Group: {0} Id: {1} Host: {2}", group, id, host);
}

Group: BTeam Id: 1234 Host: BTeamHost

Group: CTeam Id: 1234 Host: BTeamHost


Solution

  • You can get a reference to the <CCC> elements by calling ElementsAfterSelf on group. This prints both groups:

    XDocument xdoc = XDocument.Load(xml);
    foreach (XElement group in xdoc.Root.Descendants("AAA").Elements("Group"))
    {
        var ddd = group.ElementsAfterSelf("CCC").Descendants("DDD");
        var id = ddd.Descendants("Id").FirstOrDefault().Value;
        var host = ddd.Descendants("Host").FirstOrDefault().Value;
        Console.WriteLine("Group: {0} Id: {1} Host: {2}", group.Value, id, host);
    }