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!
I can't find EndElement for XML nodes in tree. Help please.
Collapse
X
-
Tags: None
-
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); } }
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...
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; }
Comment