写出XML内容
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
*
*写出xml文件的注意内容
*/
public class DomWriter2 {
public static void main(String[] args) throws Exception {
String str="F:\\JAVAEEtest\\javatestOne\\src\\contact.xml";
Document document = new SAXReader().read(new File("./src/stduent.xml"));
OutputFormat fromat=OutputFormat.createCompactFormat();
OutputFormat fromat1=OutputFormat.createPrettyPrint();
/***
* 影响了xml的文档声明的Encoding编码
* 影响了xml内容保存的编码
*/
fromat.setEncoding("utf-8");
OutputStream outStream = new FileOutputStream(str);
XMLWriter writer = new XMLWriter(outStream,fromat);
writer.write(document);
}
}
增删改
mport java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
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;
/**
* 修改xml文件
* 添加 : 文档 标签 属性
* 修改 :属性值 文本内容
* 删除 :标签 属性
*修改xml文件
* 1读取到原来的xml文件(document对象)
* 2.操作document对象,修改xml文件信息(document对象)
* 3.修改后的docum对象写到xml文件中(覆盖源文件)
*/
public class DomAlter {
public static void main(String[] args) throws Exception {
String str="F:\\JAVAEEtest\\javatestOne\\src\\contact.xml";
/**
* 添加
*
*/
Document doc = DocumentHelper.createDocument();
Element addElement = doc.addElement("contact-list");
Element conELem = addElement.addElement("contact");
Element nameElem = conELem.addElement("name");
conELem.addAttribute("id", "001");
conELem.addAttribute("name", "张三");
OutputStream outStrem = new FileOutputStream(str);
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(outStrem,format);
writer.write(doc);
Document document = new SAXReader().read(new File("./src/stduent.xml"));
Element element = document.getRootElement().element("contact");
Attribute attr = element.attribute("id");
attr.setValue("002");
element.addAttribute("id", "004");
Element element2 = document.getRootElement().element("contact").element("name");
element2.setText("王五");
Element element3 = document.getRootElement().element("contact");
element3.detach();
element3.getParent().remove(element3);
Element element5 = document.getRootElement().element("contact");
Attribute attr1 = element5.attribute("id");
attr1.detach();
}
}