【发布时间】:2011-05-05 17:34:49
【问题描述】:
在我的应用程序中,我正在解析一个 xml,这是一个结构问题:
<answers>
<answer value="A">A</answer>
<answer value="B">B</answer>
<answer value="C">C</answer>
</answers>
我正在用 XML DOM 解析它:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
效果很好,根据答案项目,我正在创建这样的 RadioButtons:
NodeList answers = doc.getElementsByTagName("answers").item(0).getChildNodes();
int j = 0;
RadioGroup group = new RadioGroup(this);
RadioButton button1 = new RadioButton(this);
button1.setId((i+1)*100+(j++));
button1.setText(answers.item(1).getChildNodes().item(0).getNodeValue());
button1.setTextColor(Color.BLACK);
RadioButton button2 = new RadioButton(this);
button2.setId((i+1)*100+(j++));
button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue());
button2.setTextColor(Color.BLACK);
RadioButton button3 = new RadioButton(this);
button3.setId((i+1)*100+(j));
button3.setText(answers.item(3).getChildNodes().item(0).getNodeValue());
button3.setTextColor(Color.BLACK);
这段代码在模拟器 SDK v.7 (Android 2.0) 中完美运行,而我的 HTC Desire 在 Android 2.1u1 (so SDK v.8) 上运行
但在设备中,我在这条线上出现错误 button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue()); 猜测答案中没有 .item(2) - 但它必须是......我在模拟器中调试这段代码,发现 answers.item(0) 是TextNode 包含 XML 节点“answers”的名称...
但确实我有点困惑,在解析这个 XML 时一切都搞砸了,因为我仍然需要计算我有多深以及何时调用哪个元素(节点)上的索引......但我仍然发现这个实现比使用SAX简单得多...
Java 中的 PHP 有没有类似于 SimpleXml 的东西???
无论如何,我的主要问题是:应用程序如何在模拟器中完美运行,而在设备上它会在我尝试为 button2 设置文本的行抛出 NullPointerException?
非常感谢您的帮助!!!
【问题讨论】:
-
哦,当我直接在devicem上输出setText()值时,
button1.setText(answers.item(1).getChildNodes().item(0).getNodeValue());被正确处理并且输出了值,而下一项button2.setText(answers.item(2).getChildNodes().item(0).getNodeValue());抛出了一个错误...所以我完全不明白... -
我的建议:在 Android 中停止使用文档生成器来解析 XML,改用简单库 (simple.sourceforge.net),这里有一篇关于它的博客文章 (massaioli.homelinux.com/wordpress/2011/04/21/…)
-
@RobertMassaioli:嗯,我看过了,它看起来不错,但仍然不是很简单-您必须为 XML 中的每个“对象”编写和定义一个类(因此对于每个标签)-哪里有简化???是的,也许在解析 XML 时,它更简单,但是您必须生成可能多两倍的代码......但是 - 我会在有时间的时候尝试一下......
-
@shadyyx 这不是真的,你不需要为每个标签写一个类。看看 Simple 中的路径注解,它允许您使用 XPath 表达式映射多个嵌套的 XML 元素和属性。
标签: android xml dom xml-parsing