概念:DOM是Document Object Model的简称,即文档数据模型。
Oracle公司提供了JAXP(Java API for XML Processing)来解析XML。JAXP会把XML文档转换成一个DOM树,JAXP的三个包都在JDK中。
org.w3c.dom;W3C推荐的解析文档的接口
org.xml.sax;使用SAX解析XML文档的接口
javax.xml.parsers;解析器工厂工具
一、使用DOM解析XML文档的步骤
1.创建解析器工厂对象,即DocumentBuilderFactory对象
2.由解析器工厂创建解析器对象,即DocumentBuilder对象
3.由解析器对象解析XML文档构建相应的DOM树,创建Document对象
4.以Document对象为起点对DOM树的节点进行增加、删除、修改、查询等操作
5.保存XML数据文档
二、案例
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<PhoneInfo>
<Brand name="华为">
<Type name="P9" />
<Item>
<title>标题信息</title>
<link>连接</link>
<description>描述</description>
<pubDate>2016-11-12</pubDate>
</Item>
</Brand>
<Brand name="苹果">
<Type name="iPhone5" />
<Type name="iPhone6" />
</Brand>
<Brand name="SAMSUNG">
<Type name="Note7" />
</Brand>
<Brand name="SAMSUNG">
<Type name="Note7" />
</Brand>
<Brand name="三星">
<Type name="Note7" />
</Brand>
<Brand name="三星">
<Type name="Note7" />
</Brand>
</PhoneInfo>
1.使用DOM读取手机收藏信息
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; /**
* DOM解析xml文档
* @author Administrator
*
*/
public class PhoneInfoShow { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{
//得到DOM解析器的工厂实例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM工厂获得DOM解析器
DocumentBuilder builder = dbf.newDocumentBuilder();
//解析xml文档,得到一个Document对象,即DOM树
Document phoneInfo = builder.parse("src/PhoneInfo.xml");
//得到所有Brand节点列表信息
NodeList brandList = phoneInfo.getElementsByTagName("Brand");
//循环Brand信息
for (int i = 0; i < brandList.getLength(); i++) {
//获取第i个Brand元素信息
Node node = brandList.item(i);
Element brand = (Element)node;
//获取元素属性值
String brandValue = brand.getAttribute("name");
System.out.println("手机品牌:"+brandValue);
//获取brand元素下的所有子元素
NodeList types = brand.getElementsByTagName("Type");
for (int j = 0; j < types.getLength(); j++) {
/*Node item = types.item(j);
Element type = (Element)item;*/
Element type = (Element)types.item(j);
//获取子节点属性值
String typeValue = type.getAttribute("name");
System.out.println("\t型号:"+typeValue);
}
}
} }
2.查找节点信息
/**
* 查找节点信息
* @author Administrator
*
*/
public class PhoneInfo03{ public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
//得到DOM解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM工厂获得DOM解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//解析XML文档得到一个DOM树
Document phoneInfo = db.parse(new File("src/PhoneInfo.xml"));
//读取pubDate
NodeList list = phoneInfo.getElementsByTagName("pubDate");
//pubDate元素节点(转换)
Element pubDateElement = (Element)list.item(0);
//读取文本节点
String pubDate = pubDateElement.getFirstChild().getNodeValue();
System.out.println(pubDate);
} }
三、使用DOM维护XML数据
1.添加信息
import java.io.FileOutputStream;
import java.io.IOException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException; /**
* 添加手机收藏信息
* @author Administrator
*
*/
public class PhoneInfoAdd { public static void main(String[] args) throws TransformerException, SAXException, IOException, ParserConfigurationException {
//解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//DOM文档
Document phone = db.parse("src/PhoneInfo.xml");
/*创建brand节点*/
Element brand = phone.createElement("Brand");
brand.setAttribute("name","三星");
/*创建type节点*/
Element type = phone.createElement("Type");
type.setAttribute("name", "Note7");
//建立父子关系
brand.appendChild(type);
Element phoneElement = (Element)phone.getElementsByTagName("PhoneInfo").item(0);
phoneElement.appendChild(brand); //保存xml文件
/*使用传输工厂*/
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
/*创建数据源*/
DOMSource domSource = new DOMSource(phone);
/*设置编码类型*/
transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
/*创建目标数据*/
StreamResult result = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
/*把DOM树转换为xml文件*/
transformer.transform(domSource, result); } }
2.修改信息
import java.io.FileOutputStream;
import java.io.IOException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; public class PhoneInfoEdit { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
//解析xml得到DOM对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document phone = db.parse("src/PhoneInfo.xml");
//找到修改的菜单
NodeList brand = phone.getElementsByTagName("Brand");
for (int i = 0; i < brand.getLength(); i++) {
Element brandElement = (Element)brand.item(i);
//得到Brand的name属性
String brandName = brandElement.getAttribute("name");
if ("三星".equals(brandName)) {
brandElement.setAttribute("name","SAMSUNG");
}
}
//保存xml文件
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
/*创建DOM源*/
DOMSource xmlSource = new DOMSource(phone);
/*设置编码类型*/
transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
Result outputTarget = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
//写入文件
transformer.transform(xmlSource, outputTarget );
} }
3.删除信息
import java.io.FileOutputStream;
import java.io.IOException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; /**
* 删除节点
* @author Administrator
*
*/
public class PhoneInfoDel { public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
//解析xml文档
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
Document phone = documentBuilder.parse("src/PhoneInfo.xml");
//找到要删除的节点
NodeList brand = phone.getElementsByTagName("Brand");
//通过遍历Brand找到要删除的节点
for (int i = 0; i < brand.getLength(); i++) {
Element brandElement = (Element)brand.item(i);
//获取Brand节点属性
String brandName = brandElement.getAttribute("name");
//查找需要的节点
if ("SAMSUNG".equals(brandName)) {
//获取父节点,利用父节点删除这个节点
brandElement.getParentNode().removeChild(brandElement);
}
}
/*for (int i = 0; i < brand.getLength(); i++) {
Element brandElement = (Element)brand.item(i);
//得到Brand的name属性
String brandName = brandElement.getAttribute("name");
if ("三星".equals(brandName)) {
//修改属性
brandElement.setAttribute("name","SAMSUNG");
//获取父节点,利用父节点删除这个节点
brandElement.getParentNode().removeChild(brandElement);
}
}*/
//写入xml
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource xmlSource = new DOMSource(phone);
//设置编码
transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
Result outputTarget = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
transformer.transform(xmlSource, outputTarget);
/*TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
创建DOM源
DOMSource xmlSource = new DOMSource(phone);
设置编码类型
transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
Result outputTarget = new StreamResult(new FileOutputStream("src/PhoneInfo.xml"));
//写入文件
transformer.transform(xmlSource, outputTarget );*/ } }
此外,还可以使用DOM4J解析XML文档会更加方便。