Java: How to determine the depth level during XML parsing using SAX
Asked Answered
H

2

2

I am extending org.xml.sax.helpers.DefaultHandler to parse a XML. How can you determine the depth level during parsing?

for example:

<?xml version="1.0" encoding="utf-8"?>
<jsk:Dataset gml:id="Dataset1" ....>
    <gml:description>....</gml:description>
    <gml:boundedBy>
        ...
    </gml:boundedBy>
</jsk:Dataset>

<jsk:Dataset> tag is on level 0

<gml:description> and <gml:boundedBy> tags are on level 1 and so on...

any guidance on the right direction is appreciated.

Hawaii answered 6/6, 2011 at 6:6 Comment(0)
C
3

The DefaultHandler class indicates that it is processing a new element via the startElement method, and that it has finished processing the same using the endElement method. You can hook onto these methods by overriding them in your child class.

The approach stated in the other answer of using an instance field to store state can be used in this case as well. Increment on entering startElement and decrement on exiting endElement.

Courcy answered 6/6, 2011 at 6:17 Comment(3)
do you mean by storing the name on the startElement(), then check if it exits on endElement with the name?Hawaii
That is not be necessary if you want the level and nothing else. Valid XML will require that each start tag be closed by an appropriate ending tag, so you will always be in a safe state. If you increment on startElement, with value starting at -1, then DataSet will have value 0, description will have 1, and boundedBy also as 1 for the value becomes 0 on ending the description tag. You'll need to think of each tag as an event. The more start events you encounter without the end events, the larger is the depth count, before you enter a phase where end events will begin to match the start events.Courcy
Thanks a lot. I got it. Clear Explanation by Vineet.Hawaii
D
2

Every time SAXListener.startTag() is called, the depth is increasing. Every time SAXListener.endTag() is called, the depth is decreasing.

increment/decrement an instance field of your handler class in these callback methods to keep track of how deep you are.

Dowdell answered 6/6, 2011 at 6:13 Comment(3)
Sorry I can't find SAXListener.Hawaii
startTag() and endTag() are methods that has no any parameter to refer (based on your given method description). How can I determine the current depth?Hawaii
I see by adding an instance field.. same approach with Vineet, isn't?Hawaii

© 2022 - 2024 — McMap. All rights reserved.