2013-02-16 66 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; 
     } 
    } 
}