I’m trying to use XElement to find out the parent node of a attribute Id. See example below
This is my data..
<Data>
<Description>MASTER</Description>
<Data>
<Description>Parent1</Description>
<Data id="GUID1" Description="THIS IS A TEST" />
<Data id="GUID2" Description="THIS IS A TEST" />
<Data id="GUID3" Description="THIS IS A TEST" />
</Data>
<Data>
<Description>Parent2</Description>
<Data id="GUID4" Description="THIS IS A TEST" />
<Data id="GUID5" Description="THIS IS A TEST" />
</Data>
<Data id="GUID6" Description="THIS IS A TEST" />
</Data>
If I want to find out “GUID6” and “GUID1” parents the result would be for GUID6 = “MASTER”
and for GUID1=”MASTERParent1″ but I my results are incorrect. Please can someone help me.
I also want the output to be “MASTER.Parent1” so it splits up the master and parent by using a “dot”
Here is my code
protected void Page_Load(object sender, EventArgs e)
{
var s = "<Data><Description>MASTER</Description><Data><Description>PARENT1</Description><Data id=\"GUID1\" Description=\"THIS IS A TEST\" /><Data id=\"GUID2\" Description=\"THIS IS A TEST\" /><Data id=\"GUID3\" Description=\"THIS IS A TEST\" /></Data><Data><Description>PARENT2</Description><Data id=\"GUID4\" Description=\"THIS IS A TEST\" /><Data id=\"GUID5\" Description=\"THIS IS A TEST\" /></Data><Data id=\"GUID6\" Description=\"THIS IS A TEST\" /></Data>";
var doc = XElement.Load(new StringReader(s));
var result = (from data in doc.Descendants("Data").Where(x => x.Attribute("id") != null)
select new
{
Id = data.Attribute("id").Value,
Decription = data.Attribute("Description").Value,
Parent = data.Parent.Value
}).ToList();
}
I feel like your example and what you are asking for don’t match up. See if my interpretation is what you are looking for.
results in this output