简体   繁体   English

使用Sax解析具有相同标签的XML元素

[英]Parse XML element with same tag using Sax

Hi guys i have a problem when i try to parse a xml element with same tag 嗨,大家好,我尝试解析带有相同标签的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>

I can parse all the others stuff but i can only parse the last "choice" 我可以解析所有其他内容,但只能解析最后一个“选择”

here is the part of the code for parsing 这是解析代码的一部分

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);
        }

I guess what is happening now is that you are setting the choice, but then you set it again (replacing it). 我猜现在正在发生的事情是您正在设置选择,但是随后又重新设置了(替换它)。 So you only get the last. 因此,您只能获得最后一个。

You must add each choice to a List and then question.setChoices(choices) where choices is a List . 您必须将每个选择添加到列表中,然后添加question.setChoices(choices) ,其中choices是一个List。 (When you get a "choice" you do choices.add(xmlInnetText.toString().trim()); (当您获得“选择”时,您可以进行choices.add(xmlInnetText.toString().trim());

Edit : also as @rmlan said it doesn't seem you would ever get to "choice". 编辑 :也正如@rmlan所说,看来您永远都不会“选择”。 You don't need to do an if inside the "choices" if . 你并不需要做的if里面的“选择” if The "choice" if can be at the same level as the others if s. if s”, if “选择”可以与其他选择处于同一级别。 Aside this fact the answer above true: you need a List to save each "choice". 除了这个事实以外,上述答案还不错:您需要一个列表来保存每个“选择”。

Edit2 : 编辑2

You need something like this: 您需要这样的东西:

(...)

} 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