wood burning stoves 2.0*
The moose likes XML and Related Technologies and the fly likes Find Level of Element in XML Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Find Level of Element in XML" Watch "Find Level of Element in XML" New topic
Author

Find Level of Element in XML

Mike Jeya
Ranch Hand

Joined: Apr 15, 2004
Posts: 54
Hi Guys,

I need to find the Level number of a Node in a XML file.
I am not able to track that.Can anyone help me out?

for ex:

<root>
<parent1>
<child1>
<child2>
</child2>
</child1>
</parent1>

<parent2>
<child21>
</child21>
</parent2>
<parent3>
</parent3>
</root>

I have to get the level of root as 0 and parent1, parent2 as 1 and child1,child21 as 2 etc..

Thanks in Advance
Balaji Loganathan
author and deputy
Bartender

Joined: Jul 13, 2001
Posts: 3150
Originally posted by Mike Jeya:

I have to get the level of root as 0 and parent1, parent2 as 1 and child1,child21 as 2 etc..

Thanks in Advance

Have you tried position() function in XSLT (if you are using xslt)


Spritle Software Blogs
Lasse Koskela
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
The position() function will not work but if you're using the DOM API, you can write a simple method like this:

Note that I didn't even compile the above, let alone write a unit test for it, so it might need some tweaking.


Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Find Level of Element in XML
 
Similar Threads
XSD
Confusion in JAXP DOM parser
string manipuation
Can an XML Node be converted to a String
Dtd generation