2013-02-16 71 views
0

我有一个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”。

+0

ü得到什么错误? – 2013-02-16 19:02:53

回答

0

您正在查看<dimensions>标记,而不是ab。看:

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

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; 
     } 
    } 
}