【问题标题】:How to get attibute and values in xml parsing in android?如何在android中的xml解析中获取属性和值?
【发布时间】:2012-07-12 09:51:49
【问题描述】:

我有一个 xml 文件,格式为

<question_choices>
<question id="499">What do you call a chicken with bad sunburn</question>
<choices1 id="2231">Burned Chicken</choices1>
<choices2 id="2230">Fried Chicken</choices2>
<choices3 id="2232">Dead Chicken</choices3>
<choices_answer>Fried Chicken</choices_answer>
</question_choices>

我必须在解析过程中同时获取 id 和值。此外,我在 3 个不同的按钮中设置了这些选项。所以当我单击这些选项时,我必须获取值并且还必须保存相应的 id。我试过了使用 getAttributes() 但我不知道在哪里以及如何使用。所以它没有成功。

    final XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element
    final NodeList nl = doc.getElementsByTagName(KEY_QUESTION);         
        // looping through all item nodes <item>
         for(int j=0;j<nl.getLength();j++)
         {
            Element e = (Element) nl.item(j);
            listnew[j]=parser.getValue(e,KEY_QUEST); 
            options1[j]= parser.getValue(e, KEY_CHOICE1);
                        options2[j]= parser.getValue(e, KEY_CHOICE2);
                        options3[j]= parser.getValue(e, KEY_CHOICE3);
        }
      TextView question = (TextView)findViewById(R.id.question);
      question.setText(listnew[x]);

      opt1 = (Button)findViewById(R.id.opt1);
      opt1.setText(options1[x]);
      opt1.setOnClickListener(myOptionOnClickListener);

      opt2 = (Button)findViewById(R.id.opt2);
      opt2.setText(options2[x]);
      opt2.setOnClickListener(myOptionOnClickListener);

      opt3 = (Button)findViewById(R.id.opt3);
      opt3.setText(options3[x]);
      opt3.setOnClickListener(myOptionOnClickListener);

      x++; 
     }

我正在使用DOM解析器进行解析。点击的选项必须保存。我应该怎么做?

【问题讨论】:

标签: android xml-parsing


【解决方案1】:

试试这个:

 Document doc = parser.getDomElement(xml);
 String idQuestion = doc.getElementsByTagName("question").item(0)
                      .getAttributes().getNamedItem("id").getNodeValue();
 String idChoise1 = doc.getElementsByTagName("choices1 ").item(0)
                      .getAttributes().getNamedItem("id").getNodeValue();
 ...

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多