xml如下:
<?xml version="1.0" encoding="GB2312"?><root>
<data>
<list0>SJCZ_INFO</list0>
<list1>QXCZ_INFO</list1>
<list2>USER_INFO</list2>
<list3>DEPT_INFO</list3>
<list4>COMP_INFO</list4>
</data>
</root>
我写得读取方法:
public void ReadXml(String path){
try {
File file = new File(path);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(file);
NodeList nl = document.getElementsByTagName("data");
for (int i = 0; i < nl.getLength(); i++) {
System.out.println(document.getElementsByTagName("list"+String.valueOf(i)).item(i).getFirstChild().getNodeValue());
System.out.println("读取xml成功!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
结果只有:SJCZ_INFO。是不是我nodelist取得有问题,该怎么取才可以循环??
------解决方案--------------------
- Java code
几行代码。。 // w3c读取xml @SuppressWarnings("unchecked") public static void readXML4() { File f = new File("f:/test.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); org.w3c.dom.Document doc = builder.parse(f); NodeList nl = doc.getElementsByTagName("data"); for (int k = 0; k < nl.getLength(); k++) { System.out.println(nl.item(k).getTextContent()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }