首页 > 代码库 > java dom4j创建 ,修改 ,删除 xml文件内容

java dom4j创建 ,修改 ,删除 xml文件内容

 

 

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class writer3 {
    @Test

/**
创建xml 节点信息

*/
public void modify1(){ Document doc=DocumentHelper.createDocument(); Element rootelem=doc.addElement("contactList"); Element contactelem= rootelem.addElement("contact"); contactelem.addAttribute("id","001").addAttribute("name","eric"); //直接在节点上写入属性值 contactelem.addElement("name").addText("张三"); //增加标签 name 内容是文本 contactelem.addElement("age").addText("20"); //增加标签 age 内容属于文本 //无论 是创建 ,修改,还是删除后都要 写出到文件中 FileOutputStream out=new FileOutputStream("e:/contact2.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer= new XMLWriter(out,format); writer.write(doc); writer.close();

 

创建效果如下:

<?xml version="1.0" encoding="utf-8"?>

<contactList> 
  <contact id="001" name="eric"> 
    <name>jimi</name>  
    <age>20</age> 
  </contact> 
</contactList>

 

 

修改代码段:

    @Test
    public void modify3() throws Exception   {
        
       //修改就这三行代码
        Document doc= new SAXReader().read(new File("e:/contact2.xml"));
        Element name=doc.getRootElement().element("contact").element("name");
        name.setText("jimi");

FileOutputStream out
= new FileOutputStream("e:/contact2.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(out,format); writer.write(doc); writer.close(); }

 

  

java dom4j创建 ,修改 ,删除 xml文件内容