DOM把XML文映射成一个倒挂的树.
使用DOM解析XML文档的步骤:
(1)创建解析器工厂对象
(2)由解析器工厂对象创建解析器对象
(3)由解析器对象对指定XML文件进行解析,构建相应DOM树,创建Document对象
(4)以Document对象为起点对DOM树的节点进行增删改查操作。
//xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Pet [
<!ELEMENT pet (dogs,cat)>
<!ELEMENT dogs (dog*)>
<!ELEMENT dog (name,age,sex)>
<!ATTLIST dog id CDATA #REQUIRED>
<!ELEMENT cat (name,age,sex)>
]>
<pet>
<dogs>
<dog id="1">
<name>aa</name>
<age>10</age>
<sex>10</sex>
</dog>
<dog id="2">
<name>bb</name>
<age>20</age>
<sex>20</sex>
</dog>
</dogs>
<cat>
<name>kitty</name>
<age>5</age>
<sex>男</sex>
</cat>
</pet>
//xml解析代码:
package Test;
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 class Pet{
public static void main(String[] args){
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbf.newDocumentBuilder();
Document document=db.parse("src/Test/Pet.xml");
NodeList dogList=document.getElementsByTagName("dog");
System.out.println("一共有"+dogList.getLength()+"只狗狗");
for(int i=0;i<dogList.getLength();i++){
Node dog=dogList.item(i);
Element elem=(Element)dog; (方:将node转化成element)
String id=elem.getAttribute("id");
System.out.println(id);
for(Node node=elem.getFirstChild();node!=null;node=node.getNextSibling()){
if(node.getNodeType()==Node.ELEMENT_NODE){
String name=node.getNodeName();
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();
}
}
}
//程序运行结果:
一共有2只狗狗
1
name:aa
age:10
sex:10
2
name:bb
age:20
sex:20