dom4j xml文档 增加节点

 

增加节点

要操作的xml文档:student.xml




 
 张三
 18
 

 
  李四
  20
 

代码:

package mydom4j;

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

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class AddNodeTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  SAXReader saxReader=new SAXReader();
  try {
   Document doc=saxReader.read(new File("student.xml"));
   
   Element root=doc.getRootElement();
   //System.out.println(root.getName());
   Element resource=root.addElement("student");
   Element age=resource.addElement("age");
   Element name=resource.addElement("name");
   age.setText("05");
   name.setText("王震");
   OutputFormat opf=new OutputFormat("\t",true,"UTF-8");
   opf.setTrimText(true);
   XMLWriter writer=new XMLWriter(new FileOutputStream("out.xml"),opf);
   writer.write(doc);
   writer.close();
   //System.out.println(root.getName());
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

你可能感兴趣的:(log4j)