2015-04-04 37 views
0

我正在使用SAX解析器解析Android應用程序上的RSS提要的XML文件,有時解析項目的pubDate沒有完成(不完整字符)。JAVA/SAX - 使用XML解析器丟失字符

例:

實際pubdate的星期四,2015年4月2日12點23分41秒0000

解析的pubdate的結果:星期四,

下面是代碼我在解析器句柄中使用:

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 
     if ("item".equalsIgnoreCase(localName)) { 
      currentItem = new RssItem(url); 
     } else if ("title".equalsIgnoreCase(localName)) { 
      parsingTitle = true; 
     } else if ("link".equalsIgnoreCase(localName)) { 
      parsingLink = true; 
     } else if ("pubDate".equalsIgnoreCase(localName)) { 
      parsingDate = true; 
     } 
    } 

    @Override 
    public void endElement(String uri, String localName, String qName) throws SAXException { 
     if ("item".equalsIgnoreCase(localName)) { 
      rssItems.add(currentItem); 
      currentItem = null; 
     } else if ("title".equalsIgnoreCase(localName)) { 
      parsingTitle = false; 
     } else if ("link".equalsIgnoreCase(localName)) { 
      parsingLink = false; 
     } else if ("pubDate".equalsIgnoreCase(localName)) { 
      parsingDate = false; 
     } 
    } 

    @Override 
    public void characters(char[] ch, int start, int length) throws SAXException { 
     if (parsingTitle) { 
      if (currentItem != null) { 
       currentItem.setTitle(new String(ch, start, length)); 
       parsingTitle = false; 
      } 
     } else if (parsingLink) { 
      if (currentItem != null) { 
       currentItem.setLink(new String(ch, start, length)); 
       parsingLink = false; 
      } 
     } else if (parsingDate) { 
      if (currentItem != null) { 
       currentItem.setDate(new String(ch, start, length)); 
       parsingDate = false; 
      } 
     } 
    } 

字符丟失是非常隨機的,每次運行應用程序時都會發生在不同的XML項目中。

回答

0

您假設每個元素只有一個characters()調用。這不是一個安全的假設。建立您的字符串超過1+致電characters(),然後將其應用於endElement()

或者,更好的是,使用a number of existing RSS parser libraries中的任何一個。

+0

謝謝,我結束了關於字符串生成器的建議,它工作! – pUdiN 2015-04-04 23:07:31