package com.heilong.test;
/**
* deo4j解析
*/
import java.io.FileOutputStream;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Demo{
public static void main(String[] args) throws Exception {
createDoc();
}
/**
* 修改xml内容:
* 创建文档
* 添加标签
* 添加属性
* @throws Exception
*/
public static void createDoc() throws Exception{
//创建文档
Document doc = DocumentHelper.createDocument();
//添加标签
Element contactList = doc.addElement("contactList");
Element contact = contactList.addElement("contact");
contact.addAttribute("id", "001");//为contact标签添加属性和属性值
Element name = contact.addElement("name");
name.setText("张三");
Element age = contact.addElement("age");
age.setText("25");
Element phone = contact.addElement("phone");
phone.setText("12032145753");
Element email = contact.addElement("email");
email.setText("zhangsan@qq.com");
Element qq = contact.addElement("qq");
qq.setText("769456248");
write(doc);
}
/**
* 修改xml内容:
* 修改属性值
* 修改文本
* @throws Exception
*/
public static void update() throws Exception{
Document doc = new SAXReader().read("./src/contact.xml");
/**
* 修改属性值
*/
//方式一:利用标签对象修改属性值(修改第一个contact标签的id属性值)
Element contactElt1 = (Element) doc.getRootElement().elements().get(0);
Attribute idAtr1 = contactElt1.attribute("id");
idAtr1.setValue("003");
//方式二:添加重名属性覆盖
Element contactElt2 = (Element) doc.getRootElement().elements().get(1);
contactElt2.addAttribute("id","004");
/**
* 修改文本
*/
//方式:利用文本对象修改文本
Element ageElt = doc.getRootElement().element("contact").element("age");
ageElt.setText("32");
write(doc);
}
/**
* 修改xml内容:
* 删除标签
* 删除属性
* @throws Exception
*/
public static void delete() throws Exception{
Document doc = new SAXReader().read("./src/contact.xml");
/**
* 删除标签
*/
Element ageElt = doc.getRootElement().element("contact").element("age");
//方式一:
ageElt.detach();
//方式二:
// ageElt.getParent().remove(ageElt);
/**
* 删除属性
* 删除第二个contact标签的id属性
*/
Element contactElt = (Element) doc.getRootElement().elements().get(1);
Attribute idAttr = contactElt.attribute("id");
idAttr.detach();
write(doc);
}
/**
* 将XML文档写出
* @param doc
* @throws Exception
*/
public static void write(Document doc) throws Exception{
FileOutputStream outputStream = new FileOutputStream("./src/contact_copy.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(outputStream,format);
writer.write(doc);
writer.close();
}
}