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

◇◆丶佛笑我妖孽 提交于 2019-12-11 07:44:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!