dom4j 在指定位置插入节点/元素

由于工作原因,用到dom4j操作xml,以下是dom4j中,插入Element的一些方法,以备后用
SAXReader reader = new SAXReader();
   Document doc = reader.read("conf/student.xml");
   Element root = doc.getRootElement();
   Element zhangsanNode = (Element) root.selectSingleNode(path);
   Element cloneE = (Element) zhangsanNode.clone();
   cloneE.element("age").setText(Integer.parseInt(cloneE.elementText("age"))+1+"");
   Element parent = zhangsanNode.getParent();
   parent.elements().add(2, cloneE);
   OutputFormat format = OutputFormat.createPrettyPrint();
   XMLWriter writer = new XMLWriter(new FileOutputStream("conf/student.xml"),format);
   writer.write(doc);
   writer.close();

xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
  <student>
    <name>zhangsan</name> 
    <age>18</age> 
    <gender>male</gender>
  </student> 
  <student>
    <name>lisi</name> 
    <age>22</age> 
    <age>23</age> 
    <gender>remale</gender>
  </student> 
</students>

你可能感兴趣的:(工作,xml)