Java学习:XML文件DOM解析实例源码
package com.iflytek.xml;
import java.io.FileReader;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/*
- XML的DOM解析
*/
public class TestXML {
public static void main(String[] args) {
//文档构建器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//得到xml文档构建器
try {
DocumentBuilder db = dbf.newDocumentBuilder();
//1.得到文档对象
//db.parse("test.xml");//在项目的目录里找
//获取当前类所在的路径
String path = FileReader.class.getResource("/").getFile();
System.out.println(path);
Document doc = db.parse(path + "test.xml");
Element root = doc.getDocumentElement();//获取根节点
String rootName = root.getNodeName();
System.out.println(rootName);
//2.获取xml中的节点
NodeList list = doc.getElementsByTagName("Student");
System.out.println("当前有几个Student:" + list.getLength());
//3.得到节点里面的有用信息
for(int i = 0;i < list.getLength(); i++) {
Element studentElement = (Element)list.item(i);
String id = studentElement.getAttribute("id");//获取id的属性值
System.out.println("id:" + id);
//遍历当前元素的子节点
NodeList childNodeList = studentElement.getChildNodes();
//回车符也算一个节点,所以下面必须要对齐进行筛选
System.out.println("子节点个数:" + childNodeList.getLength());
for(int j = 0; j < childNodeList.getLength(); j++) {
if(childNodeList.item(j) instanceof Element) {
Element cElement = (Element) childNodeList.item(j);
String tagName = cElement.getTagName();
String content = cElement.getTextContent();
System.out.println(tagName + ":" + content);
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果
xml文档文件存放路径
xml文件内容