问题
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.
回答1:
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
.
回答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.
来源:https://stackoverflow.com/questions/6248322/java-how-to-determine-the-depth-level-during-xml-parsing-using-sax