简体   繁体   English

如何在Java的SAX Parser中解析嵌套元素?

[英]How can I parse nested elements in SAX Parser in java?

I want to parse an XML file using SAX parser in java with this format : 我想使用以下格式的java中的SAX解析器来解析XML文件:

<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. 我很难区分交易节点的id元素和城市节点的id元素。

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. 然后,在startElement回调中,如果开始标记为Deals ,则将inDeals设置为true。 Similarly for Deal and city . 对于Dealcity In the endElement callback, do the inverse (eg end tag == Deals , set inDeals back to false). 在endElement回调中,进行相反操作(例如,结束标记== Deals ,将inDeals设置回false)。 In your characters method, or however you're processing the tag, just handle based on the state of the parser at that time. 在您的character方法中,或者您正在处理标签的方法中,只需根据当时解析器的状态进行处理即可。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM