Search code examples
c#xmllinqarchitecturexelement

How to find out a child's parent?


I'm trying to use XElement to find out the parent node of a child. See the example below. This is my data:

<Data>
    <Description>King</Description>
    <Data>
        <Description>Mike</Description>
        <Data id="GUID1" Description="THIS IS A TEST" />
    </Data>
    <Data>
        <Description>David</Description>
        <Data id="GUID2" Description="THIS IS A TEST" />
        <Data id="GUID3" Description="THIS IS A TEST" />
    </Data>
    <Data id="GUID4" Description="THIS IS A TEST" />
</Data>

So the Parent(King) has two childs Mike and David. What I want is to find out who is the Parent of "David" How can I find this out?

Here is my code below:

protected void Page_Load(object sender, EventArgs e)
{
    var s =
     @"<Data>
           <Description>King</Description>
           <Data>
             <Description>Mike</Description>
             <Data id=""GUID1"" Description=""THIS IS A TEST"" />
           </Data>
           <Data>
             <Description>David</Description>
             <Data id=""GUID2"" Description=""THIS IS A TEST"" />
             <Data id=""GUID3"" Description=""THIS IS A TEST"" />
           </Data>
           <Data id=""GUID4"" Description=""THIS IS A TEST"" />
       </Data>";

    var doc = XElement.Load(new StringReader(s));

    var result = (from data in doc.Descendants("Data")
                  where (string)data.Attribute("id") != null
                  select new
                  {
                      Id = data.Attribute("id").Value,
                      Decription = data.Attribute("Description").Value,
                      Child = data.Parent.Element("Description").Value,
                      Parent = data.Parent.Parent.Value **** THIS LINE ****
                  });

    foreach (var element in result)
    {
        Console.WriteLine("{0} {1}", element.Id, element.Decription);
    }
}

I tried everything but no luck. I keep getting the whole parent results for data.Parent.Parent.Value ="KingMikeDavid" which is wrong. How do I return just "King" without its children?


Solution

  • data.Parent.Parent refers to the entire Data element, and its value is the combined value of its descendants. You need the value of its Description child:

    Parent = data.Parent.Parent == null ? null :
        data.Parent.Parent.Element("Description").Value