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.

Tahir Akhtar
  • 11,385
  • 7
  • 42
  • 69
eros
  • 4,946
  • 18
  • 53
  • 78

2 Answers2

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.

Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
  • do you mean by storing the name on the startElement(), then check if it exits on endElement with the name? – eros Jun 06 '11 at 06:46
  • 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. – Vineet Reynolds Jun 06 '11 at 06:52
  • Thanks a lot. I got it. Clear Explanation by Vineet. – eros Jun 06 '11 at 06:55
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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Sorry I can't find SAXListener. – eros Jun 06 '11 at 06:46
  • 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? – eros Jun 06 '11 at 06:49
  • I see by adding an instance field.. same approach with Vineet, isn't? – eros Jun 06 '11 at 06:50