我有一个带有文件res / raw / lvl.xml
的android项目<?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”。
答案 0 :(得分:0)
您正在查看<dimensions>
代码,而不是a
和b
。看:
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
int a = Integer.parseInt(node.getNodeValue().trim());
您将获得名为0
的第一个(索引dimensions
)元素。不是它的孩子。
您看到的值(\t\t\n\t
)是删除子节点后dimensions
'内容的剩余部分。
答案 1 :(得分:0)
无法理解你究竟想要做什么...但是......如果有帮助,你可以参考下面
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;
}
}
}