开发者

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

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 开发者_C百科on level 0

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

any guidance on the right direction is appreciated.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜