XML文件
<?xml version="1.0" encoding="gb2312"?>
<classRoom>
<student>
<name>王五</name>
<age>19</age>
</student>
<student>
<name>张三</name>
<age>22</age>
</student>
<student>
<name>李四</name>
<age>33</age>
</student>
</classRoom>
读取程序
package T20;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
public class ReaderXML {
/**
* @param args
*/
public static void main(String[] args) {
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = db.parse(new File("MyXml.xml"));
NodeList nl = doc.getElementsByTagName("classRoom");
Element n = (Element) nl.item(0);
// System.out.println(n.getElementsByTagName("Student").getLength());
for (int i = 0; i < n.getElementsByTagName("student").getLength(); i++) {
String name = n.getElementsByTagName("name").item(i)
.getFirstChild().getNodeValue();
int age = Integer.parseInt(n.getElementsByTagName("age")
.item(i).getFirstChild().getNodeValue());
System.out.println(name);
System.out.println(age);
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
} catch (SAXException e) {
System.out.println(e.getMessage());
}
}
}