2012-04-26 52 views
0

我有一個XML,我解析有一個字段包含非常長的文本,但不知何故它被解析器,這是因爲我只是使用字符串讓這些字符應該使用字符串緩衝區或構建器。我想要的只是通過標籤提取價值。Android SAX的XML解析器與字符串或Stringbuilder或Stringbuffer

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

    if (elementOn) { 
    // its not reading element value, though tag is read. 
     elementValue = new String(ch, start, length); 
     elementOn = false; 
    } 
} 

這是文字:

<description> 
    <![CDATA[ 
    Former CPI MLA Manish Kunjam, who returned on Thursday after, theis is a long long text very long that its being dropped.......so what can be done................................................................................................... 
    ]]> 
</description> 

感謝PLZ指導我.....

回答

2

是,使用StringBuilder,因爲文本可以按塊被讀取,你可能只是讀這是第一個空行代碼。見documentation

可以在每次打startElement

private final StringBuilder mStringBuilder = new StringBuilder(); 
private String elementValue = null; 
private boolean elementOn = false; 

public final void characters(char[] ch, int start, int length) throws SAXException { 
    if (elementOn) 
     mStringBuilder.append(ch, start, length); 
} 

public final void startElement(String uri, String localName, String qName, Attributes attributes) 
     throws SAXException { 
    mStringBuilder.setLength(0); 
    if (someCondition) elementOn = true; 
} 

public void endElement(String uri, String localName, String qName) throws SAXException { 
    elementValue = mStringBuilder.toString().trim(); 
    elementOn = false; 
} 

解析器做了有關以下

<description> -> startElement("description"), reset StringBuilder 
    <![CDATA[ -> characters(""), appended to (empty) String 
    Former CPI.. -> characters("Former.."), appended 
    ]]>   -> characters(""), appended 
</description> -> endElement("description"), read text here 
<description> -> startElement("description"), reset StringBuilder all starts again 
+0

是時間重置的StringBuilder,但是這會給我一個包含所有標籤的長字符串... ..有什麼辦法我只能得到單獨的標籤... – Programmer 2012-04-26 12:18:18

+0

它應該只給你一個元素的內容,因爲每次新元素啓動時它會重置StringBuilder。 – zapl 2012-04-26 12:20:53