dom4j动态修改xml节点的值

package com.jyd;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

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

public class Test {
    
    public static void main(String[] args) {
        String tag = "subject";
        String tagValue = "2014-10-17";
        String path1 = "WebRoot/WEB-INF/classes/com/jyd/conf/task.xml";
        String path2 = "src/com/jyd/conf/task.xml";
        try {
            Document doc = new SAXReader().read("WebRoot/WEB-INF/classes/com/jyd/conf/task.xml");
            Element root = doc.getRootElement();
            List nodeList = root.selectNodes("/jive/task/collect/"+tag+"/last");
            for (int i = 0; nodeList != null && i < nodeList.size(); i++) {
                Node tagNode = (Node)nodeList.get(i);
                System.out.println(tagNode.getText());
                tagNode.setText(tagValue);
                String text = tagNode.getText();
                System.out.println(text);
                writeToFile(doc,path2 , "UTF-8");
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static boolean writeToFile(Document doc, String filePath,
            String encoding) {
        try {
             XMLWriter writer = new XMLWriter(new FileWriter(new File(  
                     filePath)));  
             writer.write(doc);  
             writer.close();  
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    } 
}
<?xml version="1.0" encoding="UTF-8"?>
<jive> 
  <task> 
    <collect> 
      <subject> 
        <last>2014-10-17</last> 
      </subject>  
      <domainref> 
        <last>2014-10-15</last> 
      </domainref>  
      <domainhour> 
        <last>2014-10-16 13时</last> 
      </domainhour>  
      <domainday> 
        <last>2014-10-15</last> 
      </domainday>  
      <flag> 
        <last/> 
      </flag>  
      <channelrefsort> 
        <last>2014-10-15</last> 
      </channelrefsort>  
      <user> 
        <last/> 
      </user>  
      <entity> 
        <last>2014-10-15</last> 
      </entity>  
      <editor> 
        <last>2014-10-15</last> 
      </editor>  
      <subjecref> 
        <last>2014-10-15</last> 
      </subjecref>  
      <subjecrefsort> 
        <last>2014-10-15</last> 
      </subjecrefsort>  
      <entitypv> 
        <last>2014-10-15</last> 
      </entitypv> 
    </collect> 
  </task> 
</jive>

代码内没有自己封装的函数 所以读代码的时候应该障碍不大;

你可能感兴趣的:(dom4j动态修改xml节点的值)