簡體   English   中英

使用Sax解析具有相同標簽的XML元素

[英]Parse XML element with same tag using Sax

嗨,大家好,我嘗試解析帶有相同標簽的xml元素時遇到問題

<question id="0">
<text> Who is the first President of the United States of America? </text>
<image> http://liisp.uncc.edu/~mshehab/api/figures/georgewashington.png </image>
<choices>
    <choice answer="true">George Washington</choice>
    <choice>Thomas Jefferson</choice>
    <choice>James Monroe</choice>
    <choice>John Adams</choice>
</choices>
</question>

我可以解析所有其他內容,但只能解析最后一個“選擇”

這是解析代碼的一部分

public void endElement(String uri, String localName, String qName)
                throws SAXException {
            if(localName.equals("text")){
                question.setText(xmlInnerText.toString().trim());
            } else if(localName.equals("image")){
                question.setImageURL(xmlInnerText.toString().trim());
            } else if(localName.equals("choices")){
                if(localName.equals("choice")){
                question.setChoice(xmlInnerText.toString().trim());
                }
            } else if(localName.equals("question")){
                questions.add(question);
            } 
            xmlInnerText.setLength(0);
        }

我猜現在正在發生的事情是您正在設置選擇,但是隨后又重新設置了(替換它)。 因此,您只能獲得最后一個。

您必須將每個選擇添加到列表中,然后添加question.setChoices(choices) ,其中choices是一個List。 (當您獲得“選擇”時,您可以進行choices.add(xmlInnetText.toString().trim());

編輯 :也正如@rmlan所說,看來您永遠都不會“選擇”。 你並不需要做的if里面的“選擇” if if s”, if “選擇”可以與其他選擇處於同一級別。 除了這個事實以外,上述答案還不錯:您需要一個列表來保存每個“選擇”。

編輯2

您需要這樣的東西:

(...)

} else if(localName.equals("choice")) {
    choices.add(setChoice(xmlInnerText.toString().trim());
} else if(localName.equals("choices")){
    question.setChoices(choices);
}                


(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM