使用DOM解析XML
?
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
?
public static void main(String[] args) {
??//1.得到DOM解析器的工厂实例
??DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
??try {
??//2.从DOM工厂获得DOM解析器
???DocumentBuilder db = dbf.newDocumentBuilder();
??//3.解析XML文档,得到一个Document,即DOM树
???Document doc = db.parse("pet1.xml");
???//4.得到所有<狗狗>节点的列表信息
???NodeList list = doc.getElementsByTagName_r("狗狗");
???//5.循环狗狗信息
???for(int i = 0 ; i < list.getLength(); i++){
??????//5.1获取第i个狗狗元素的信息
????Element dog = (Element)list.item(i);
??????//5.2获取第i个狗狗元素的id属性的值并输出
????String id = dog.getAttribute("id");?//获得标签里的属性id的值
????System.out.println("id:"+id);
??????//5.3获取第i个狗狗元素的所有子元素的名称和值并输出
????for(Node node = dog.getFirstChild(); node!=null; node=node.getNextSibling()){
?????if(node.getNodeType() == Node.ELEMENT_NODE){?//判断是否是元素节点
??????String name = node.getNodeName(); //根据节点的类型返回节点的名称
??????String value = node.getTextContent();??//得到节点里的值(一组值)
??????System.out.println(name + " " +value);
?????}
????}
???}
???
??} catch (ParserConfigurationException e) {
???e.printStackTrace();
??} catch (SAXException e) {
???e.printStackTrace();
??} catch (IOException e) {
???e.printStackTrace();
??}
????
?}