package naixi;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Demo3 {
//DOM4J->对DOM再次封装起来
public static void main(String[] args) {
Demo3 d = new Demo3();
try {
Document document = d.getDocument("src/naixi/dom.xml");
d.show(document);
d.save(document,"src/naixi/dom3.xml");
d.update(document, "src/naixi/dom4.xml");
d.add(document, "src/naixi/dom5.xml");
d.delete(document, "src/naixi/dom6.xml");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取Document对象
* @param path
* @return
* @throws Exception
*/
public Document getDocument(String path) throws Exception {
SAXReader saxReader = new SAXReader();
return saxReader.read(path);
}
/**
* 遍历Document
* @param document
*/
public void show(Document document) {
Element root = document.getRootElement();//获取根节点
//迭代获取Band元素
Iterator<Element> bandEle = root.elementIterator("Band");
while(bandEle.hasNext()) {
Element next = bandEle.next();
//输出节点的名字
System.out.println(" "+next.getName());
System.out.println(" "+next.attributeValue("name"));
Iterator<Element> typeEle = next.elementIterator("type");
while(typeEle.hasNext()) {
Element next2 = typeEle.next();
System.out.println(" "+next2.getName());
System.out.println(" "+next2.attributeValue("name"));
}
}
}
/**
* 保存
* @param document
* @param path
* @throws Exception
*/
public void save(Document document,String path) throws Exception {
//输出格式化对象
OutputFormat of = OutputFormat.createPrettyPrint();
of.setEncoding("utf-8");
//获取流 并输出
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path), of);
xmlWriter.write(document);
//刷新
xmlWriter.flush();
}
/**
* 更新节点
* @param document
* @param path
* @throws Exception
*/
public void update (Document document,String path) throws Exception{
Element root = document.getRootElement();
Iterator<Element> band = root.elementIterator("Band");
int id = 1;
while(band.hasNext()) {
Element next = band.next();
next.addAttribute("id", id+++"");
}
save(document,path);
}
/**
* 添加节点
* @param document
* @param path
* @throws Exception
*/
public void add (Document document,String path) throws Exception {
Element root = document.getRootElement();//获取根节点
Element addBand = root.addElement("Band");
addBand.addAttribute("name", "三星");
Element addType = addBand.addElement("type");
addType.addAttribute("name", "note");
save(document,path);
}
//删除节点
public void delete (Document document,String path) throws Exception {
Element root = document.getRootElement();//获取根节点
Iterator<Element> ele = root.elementIterator("Band");
while(ele.hasNext()) {
Element next = ele.next();
if("苹果".equals(next.attributeValue("name"))) {
next.getParent().remove(next);
}
}
save(document,path);
}
}