0

我有一个带有文件 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"。

4

2 回答 2

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;
        }
    }
}
于 2013-02-16T19:39:03.887 回答
0

您正在查看<dimensions>标签,而不是aand b。看:

NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
int a = Integer.parseInt(node.getNodeValue().trim());

您将获得0name 的第一个(索引)元素dimensions。不是它的孩子。

您看到的值 ( ) 是删除子节点后 ' 内容\t\t\n\t的剩余值。dimensions

于 2013-02-16T18:34:19.243 回答