【发布时间】:2017-01-24 14:09:24
【问题描述】:
我正在尝试从下面发布的xml 文件中获取id、name 和pin,并且我编写了下面发布的代码。
问题是,node.getNodeValue() 这一行总是返回 null
请告诉我如何正确地从xml 文件中获取id、name 和pin?
代码
try {
URL url = new URL(link);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("employee");
Log.i(TAG, " nodeLength:" + nodes.getLength());
for (int i = 0; i < nodes.getLength(); i ++) {
Node node = nodes.item(i);
Log.i(TAG, "Current Element :" + node.getNodeValue());//THIS LINE
}
}
catch (Exception e) {
e.printStackTrace();
}
xml
<employee_list>
<employee id="21358" pin="0000" name="www"/>
<employee id="21359" pin="0011" name="qqq"/>
<employee id="20752" pin="1011" name="Test"/>
<employee id="814" pin="1012" name="Pf"/>
<employee id="21372" pin="1013" name="Kru"/>
</employee_list>
堆栈跟踪
01-24 15:05:54.219 5624-5718/com.example. I/XmlParser: nodeLength:33
01-24 15:05:54.220 5624-5718/com.example. I/XmlParser: Current Element :null
01-24 15:05:54.220 5624-5718/com.example. I/XmlParser: Current Element :null
01-24 15:05:54.220 5624-5718/com.example. I/XmlParser: Current Element :null
01-24 15:05:54.220 5624-5718/com.example.I/XmlParser: Current Element :null
01-24 15:05:54.220 5624-5718/com.example. I/XmlParser: Current Element :null
【问题讨论】:
-
发布堆栈跟踪
-
@Rasi 发帖请看
-
试试这个
node.getAttributes().getNamedItem("id").getNodeValue()