getNodeValue()返回一些随机字符串
问题描述:
我有一个Android项目与文件RES /生/ lvl.xmlgetNodeValue()返回一些随机字符串
<?xml version="1.0" encoding="utf-8"?>
<Level>
<dimensions>
<a>5</a>
<b>5</b>
</dimensions>
.
.
.
</Level>
我的Java代码以下
InputStream input = this.getResources().openRawResource(R.raw.lvl);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = buider.parse(input);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
int a = Integer.parseInt(node.getFirstChild().getNodeValue().trim());
最后一行抛出解析例外, node.getNodeValue()。trim()是“\ t \ t \ n \ t”。
答
您正在查看<dimensions>
标记,而不是a
和b
。看:
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
int a = Integer.parseInt(node.getNodeValue().trim());
你越来越名字dimensions
的第一个(索引0
)元素。不是它的孩子。
您看到的值(\t\t\n\t
)是子节点删除后剩下的dimensions
的内容。
+0
这是一个错字。我将编辑该问题。不管怎么说,还是要谢谢你。 – user2062607 2013-02-16 18:41:52
答
无法准确了解你正在尝试做的...但..你可以参考下面是否有帮助
public class Parsing {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
Parsing parse = new Parsing();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("x.xml"));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
for (Node childNode = node.getFirstChild();
childNode != null;) {
//do something
System.out.println(childNode.getNodeName());
System.out.println(childNode.getTextContent());
Node nextChild = childNode.getNextSibling();
childNode = nextChild;
}
}
}
ü得到什么错误? – 2013-02-16 19:02:53
最后一行会抛出异常,因为下一个节点是和之间的空格。如果node.getFirstChild()不返回元素,则应该迭代兄弟元素直到找到元素节点。 –
2013-02-16 21:35:55