I can't find EndElement for XML nodes in tree. Help please.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • redredraider
    New Member
    • Aug 2009
    • 1

    I can't find EndElement for XML nodes in tree. Help please.

    I'm trying to recursively parse a tree of XML nodes. I need to be able to keep track of how deep I am in the tree at any given time. What I had planned to do is use a counter that increments when I move a level deeper into the tree and decrements when I move out of that level. To do this I need to be able to read the start elements and end elements. My code never sees the end elements though. Thanks for your help!
    Attached Files
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    I don't know what your XML actually looks like, so you might not even see an end element. MSDN looks like it says an EndElement is something like </item> which is for the actual XML. You're using XmlNode, I'm not sure if that would match up.

    However, you shouldn't need to know this... you're at the end of a branch of XML when there are no more child nodes. By that I mean, when they are null.

    Here's a very simple example of something that will run through an XmlNode, as loaded into an XmlDocument.

    Code:
    public void TraverseXML(XmlNode rootNode)
    {
      // Do something with rootNode
      ...
    
      // Traverse the children
      foreach (XmlNode childNode in rootNode.ChildNodes)
      {
        TraverseXML(childNode);
      }
    }
    Anything on top of that is just extra (like your counter), that's the core of what you need.

    That said, if you want to use the XmlNodeType in the fashion your code is, try using an XML reader instead. A quick google search turned this up...

    www.XML.com,Textuality Services,Niel Bornstein,Programming,Learning C# XML


    Good luck!

    *Edit: Oh, one more thing to add. You can always find out how deep an XmlNode is in the hierarchy by traversing up to it's parent. When the parent is null, you're at the top.

    Code:
    public int LevelsDeep(XmlNode node)
    {
      int count = 0;
      XmlNode nextNode = node.ParentNode;
      while (nextNode != null)
      {
        count++;
        node = node.ParentNode;
      }
    
      return count;
    }
    I think there might be one extra level at the top that's the document element, but don't quote me 100% on that since I'm digging it out of memory. It doesn't take too long to try it out and see.

    Comment

    Working...