How to get an XNode using Linq to XML?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Iaml

    #1

    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.Descendant s("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.
Working...