469,889 Members | 1,234 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,889 developers. It's quick & easy.

How to get an XNode using Linq to XML?

I have an XML file and the depth of each node is unpredictable.

I need to find the grandparent node which contains an element whose
certain attribute has the given value. Then I will process that
parent node.

As I said, the node's depth is unpredictable, all nodes in the xml
file have the same tag name. For example, all nodes start with things
like

<Category ... ........... />
<Category ............ />

Thus if I use the regular XmlDocument, XmlNode objects, I need to
write a recursive method to find the node whose attribute has the
given value. I haven't figured out the recursive method yet. Any
thought is highly appreciated.

That said, I do notice that if I use Linq to XML, I can simply
traverse all tree nodes by

XDocument xdoc = XDocument.Load("MyXml.xml");
var categories = from category in xdoc.Descendants("Category")
select category;

foreach(var c in categories)
{
// See below for my question about this for loop.
}

In the foreach block, I can compare the attribute value with the given
value, but how do I get *only* the parent node of the node which has
this attribute value?

I tried

XElement element = c.Parent;

but, it seems that this element goes all the way to the end of the Xml
file, which is not what I want. I only want the parent node. It's
sorta easy to get the parent node only with the regular Xml API, but I
don't know how to achieve this with the Linq to XML API. Any idea?

Thank you.
Jun 27 '08 #1
0 2491

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

18 posts views Thread by martin | last post: by
2 posts views Thread by Neil Chambers | last post: by
7 posts views Thread by shapper | last post: by
5 posts views Thread by CSharper | last post: by
4 posts views Thread by George | last post: by
reply views Thread by bob laughland | last post: by
3 posts views Thread by bob laughland | last post: by
1 post views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.