Lets say I have this xml:
<categories>
<category text="Arts">
<category text="Design"/>
<category text="Visual Arts"/>
</category>
<category text="Business">
<category text="Business News"/>
<category text="Careers"/>
<category text="Investing"/>
</category>
<category text="Comedy"/>
</categories>
I want to write a LINQ query that will return the category and it’s parent category if it has any.
For example, if I was searching for “Business News” I would want it to return an XElement containing the following:
<category text="Business">
<category text="Business News" />
</category>
If I only search for “Business”, I would just want
<category text="Business" />
So far the best I can do is use LINQ to get the element I’m searching for, then check if the parent of the node I found is the root node and adjust accordingly. Is there a better way?
The easy part is to get the path to the element:
The InDocumentOrder() is there to get the collection in the order of root, child, grandchild. The ToList() is there to avoid any unwanted effects in the next step.
Now, the less beautiful part, which maybe could be done in a more elegant way:
That’s it. Since each XElement keeps their child, we have to remove the children from each node in the path, and then we rebuild the tree.