0

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

John
  • 787
  • 4
  • 11
  • 28

2 Answers2

0

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);
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("AAA")
                .GroupBy(x => x.Element("Group"))
                .Select(x => new
                {
                    group = x.Key,
                    id = (string)x.Descendants("Id").FirstOrDefault(),
                    host = (string)x.Descendants("Host").FirstOrDefault()
                })
                .ToList();
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20