How can I parse nested elements in SAX Parser in java?

自闭症网瘾萝莉.ら 提交于 2021-02-08 06:36:40

问题


I want to parse an XML file using SAX parser in java with this format :

<Deals>
  <Deal>
   <id> 10</id>
   <title> title </title>
   <city>
     <id> 1 </id>
     ...
   </city>
  </Deal>
  ...
</Deals>

I have a problem to distinguish between the id element of Deal Node and the id element of the city node.


回答1:


One thing you can do (I've seen it around and used it -- I'm not certain it's the most efficient or effective way, but it works) is to maintain some state in your parser, whether that be a defined set of states, or some boolean flags, that describe where you are in the document. For example, you might have:

boolean inDeals = false;
boolean inDeal = false;
boolean inCity = false;

Then, in your startElement callback, if the start tag is Deals, set inDeals to true. Similarly for Deal and city. In the endElement callback, do the inverse (e.g. end tag == Deals, set inDeals back to false). In your characters method, or however you're processing the tag, just handle based on the state of the parser at that time. For example:

if(inDeal) {
    if(inCity) {
        cityId = /*the characters*/;
    } else dealId = /*the characters*/;
}


来源:https://stackoverflow.com/questions/10388047/how-can-i-parse-nested-elements-in-sax-parser-in-java

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