import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
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.TransformerConfigurationException;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* 使用Dom解析器,操作XML里面的信息
*
* @author Rick
*
* 2016-12-10下午2:32:15
*/
public class OopParseXMLDemo {
private Document document;
// 获得DOM树,获得Document对象
public void getDom() {
// 创建解析器工厂对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 解析器工厂对象创建解析器对象
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
// 解析器对象指定XML文件创建Document对象
document = builder.parse("收藏信息.xml");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 解析 收藏信息.xml,获得手机品牌和型号
public void showInfo() {
// 以Document对象为起点操作DOM数
NodeList brands = document.getElementsByTagName("Brand");
// 遍历NodeList,取出各节点
for (int i = 0; i < brands.getLength(); i++) {
// 每一个Brand节点
Node node = brands.item(i);
Element eleBrand = (Element) node;
String brandName = eleBrand.getAttribute("name");
System.out.println(brandName);
// 继续找node下面的节点,就是<type>
NodeList types = eleBrand.getChildNodes();
for (int j = 0; j < types.getLength(); j++) {
Node typeNode = types.item(j);
// 判断节点是否为元素
if (typeNode.getNodeType() == Node.ELEMENT_NODE) {
Element typeEle = (Element) typeNode;
System.out.println(" " + typeEle.getAttribute("name"));
}
}
}
}
// 保存XML文件
public void saveXML(String path) {
// 获得转换器
TransformerFactory factory = TransformerFactory.newInstance();
// ---1.--->把转换器设置一下缩进值通过setAttribute
factory.setAttribute("indent-number", 4);
try {
Transformer transformer = factory.newTransformer();
// 指定特定的转换格式
transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
// ---2.---> 增加开启缩进转换格式
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// 源
DOMSource source = new DOMSource(document);
// 目标
/*
* StreamResult result = new StreamResult(new
* FileOutputStream(path));
*/
// ---3.--->最后以流的形式OutputStreamWriter输出
StreamResult result = new StreamResult(new OutputStreamWriter(
new FileOutputStream(path), "gb2312"));
// 开始转换
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// 为xml文件添加元素
public void addEle() {
// (1)创建Brand元素
Element brand = document.createElement("Brand");
// (2)设置Brand元素的name="三星"
brand.setAttribute("name", "三星");
// (3)创建Type元素
Element type = document.createElement("Type");
// (4)设置Type元素name="Node2"
type.setAttribute("name", "Node2");
// (5)Type加到Brand里面去(添加一个孩子)
brand.appendChild(type);
// (6)再把Brand加到<PhoneInfo>里面来
document.getElementsByTagName("PhoneInfo").item(0).appendChild(brand);
saveXML("收藏信息.xml");
}
// 修改元素:为每个<Brand>添加一个id属性,取值分别为0 1 2
public void updateEle() {
// 获取到每个Brand元素
NodeList brands = document.getElementsByTagName("Brand");
for (int i = 0; i < brands.getLength(); i++) {
Node brand = brands.item(i);
Element brandEle = (Element) brand;
// 修改每一个Brand元素的属性id
brandEle.setAttribute("id", i + "");
}
saveXML("收藏信息.xml");
}
// 删除元素:删除手机品牌为“华为”的相关元素
public void deleteEle() {
// 遍历所有的Brand元素,找到Brand的name=“华为”元素
NodeList brands = document.getElementsByTagName("Brand");
for (int i = 0; i < brands.getLength(); i++) {
Node brand = brands.item(i);
Element brandEle = (Element) brand;
// 找到Brand的name=“华为”元素,将其删除
if (brandEle.getAttribute("name").equals("华为")) {
brandEle.getParentNode().removeChild(brandEle);
}
}
saveXML("收藏信息.xml");
}
public static void main(String[] args) {
OopParseXMLDemo pd = new OopParseXMLDemo();
// pd.showInfo();
pd.getDom();
// pd.saveXML("新收藏信息.xml");
// pd.addEle();
// pd.updateEle();
pd.deleteEle();
}
}