dom解析XML
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class TestDOM {
public static void main(String[] args) {
try {
//创建解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//通过解析器工厂获得DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//解析指定XML文档,得到DOM节点树对象
Document doc = db.parse("vehicles.xml");
//得到根节点下的所有子节点
NodeList vehicles = doc.getChildNodes();
System.out.println("《租车系统》中共有" + vehicles.getLength() + "种类型的车!");
//得到所有<truck>节点列表信息
NodeList truckList = doc.getElementsByTagName("truck");
System.out.println("《租车系统》中共有" + truckList.getLength() + "辆卡车!");
//遍历所有卡车
for (int i = 0; i < truckList.getLength(); i++) {
//获取索引为i的卡车
Node truck = truckList.item(i);
//获取卡车属性值并显示
Element element = (Element) truck;
//String idValue = element.getAttribute("id");
//以下是通过属性值获得属性节点,再通过属性节点getNodeValue()获得属性值
Node attr = element.getAttributeNode("id");
String idValue = attr.getNodeValue();
System.out.println("id为" + idValue + "的卡车信息为:");
//获取索引为i的卡车详细信息并输出
for (Node node = truck.getFirstChild(); node != null; node = node.getNextSibling()) {
//根据节点类型进行判断,元素节点:例如 <oil>20</oil>
if (node.getNodeType() == Node.ELEMENT_NODE){
//元素节点,节点名即为标签名:例如oil
String name = node.getNodeName();
//元素节点 <oil>20</oil>下第一个子节点为文本节点20,得到节点值20
String value = node.getFirstChild().getNodeValue();
System.out.println(" " + name + ":" + value + ";");
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}