本帖最后由 聆听 于 2012-10-28 18:12 编辑
希望对大家有所帮助!
// DOM解析
public class DOMDemo {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//取得DocumentBuilderFactory类对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//取得DocumentBuilder类对象
DocumentBuilder builder = factory.newDocumentBuilder();
//指定xml文件路径
Document doc = builder.parse(new File("D:/demo.xml"));
//得到所有的student节点
NodeList nl = doc.getElementsByTagName("student");
//System.out.println("姓名:"+nl.item(0).getFirstChild().getNodeValue());
for (int i = 0; i < nl.getLength(); i++) {
//取出每一个元素
Element e = (Element)nl.item(i);
System.out.println("姓名:"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
System.out.println("年龄:"+e.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
System.out.println("性别:"+e.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue());
}
}
}
|