SaxParser串联概率

时间:2013-08-12 10:04:19

标签: java sax saxparser

我有一个类似

的xml文件
<Event Id="258" Key="123456">
<SubEvent Id="1">
Microsoft will begin selling its &quot;Kinect&quot; full-body motion-sensing game system from November 4, while Sony launched its &quot;Move&quot; motion-controlled gaming system on September 15.  
</SubEvent>
</Event>

解析器处理程序的一部分

public void startElement(String uri, String localName,String qName, 
            Attributes atts) throws SAXException {

    if (qName.equalsIgnoreCase("event")) {
         scored = false;
         event = true;
                   if (//my condition){
                        scored = true; 
                   }
                   if (scored){
                           sb= new StringBuffer();
     }
}

public void characters(char ch[], int start, int length) throws SAXException {

    if (event) {
        event = false;
    }

    if (subevent) {
                    if (scored){
                            sb.append(new String(ch, start, length));
                    }
        subevent = false;

    }
}

但这只会回归“微软将开始销售它”

我读到解析器可能会进行多个字符调用。 如何将不同的调用连接在一起?你能解释一下逻辑流程吗?

其他信息: 我做了一个打印所有元素,看来句子的其余部分没有被调用,为什么??

 Start Element :Event
 Start Element :SubEvent
 SubEvent: 
 Microsoft will begin selling its 
 End Element :SubEvent
 End Element :Event
 Start Element :Event
 Start Element :SubEvent
 SubEvent: 
 Nintendo will sell a new version of its DS handheld device that can play games and show movies in 3D without glasses sometime before March 2011. 
 End Element :SubEvent
 End Element :Event

2 个答案:

答案 0 :(得分:0)

characters(char ch[], int start, int length)方法无法读取整行,您应将字符存储在StringBuffer中,并在endElement方法中使用它。

public void endElement(String uri, String localName, String qName) throws SAXException
{

     if (qName.equalsIgnoreCase("event")) 
     {
        System.out.println(sb.toString());
     }
     sb = new StringBuffer();
}

答案 1 :(得分:0)

解决。

public void endElement(String uri, String localName,
    String qName) throws SAXException {
         if (qName.equalsIgnoreCase("event")) {
                scored = false;
            }
            if (qName.equalsIgnoreCase("subevent")){
                subevent=false;
            }
}