Java-Dom4J增加、修改xml

package com.ntech.xml;

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

import org.dom4j.Attribute;
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 Dom4jDemo {

    public static void main(String[] args) throws DocumentException, IOException {
        // TODO Auto-generated method stub
        String filePath = "src\\tmp\\Cash_field.xml";
        File file = new File(filePath);
        if(file.exists()) {
            System.out.println("1");
        }
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
//      addElement(document,file);
        removeElement(document, file);
    }
    
    private static void addElement(Document document,File file) throws IOException {
        Element root = document.getRootElement();
        System.out.println(root.getName());
        List childList = root.elements();
        for(Element element:childList) {
            Attribute nameAttribute = element.attribute("name");
            if("对公现金来源".equals(nameAttribute.getValue())) {
                Element itemElement = element.addElement("item");
                itemElement.addAttribute("key", "500");
                itemElement.addAttribute("value", "借来的");
            }
        }
        
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(file), format);
        xmlWriter.write(document);
        xmlWriter.close();
        
        
    }
    
    private static void removeElement(Document document,File file) throws IOException {
        Element root = document.getRootElement();
        System.out.println(root.getName());
        List childList = root.elements();
        for(Element element:childList) {
            Attribute nameAttribute = element.attribute("name");
            if("对公现金来源".equals(nameAttribute.getValue())) {
                List itemList = element.elements();
                for(Element item:itemList) {
                    if("500".equals(item.attribute("key").getValue())) {
                        element.remove(item);
                    }
                }
            }
        }
        
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(file), format);
        xmlWriter.write(document);
        xmlWriter.close();
    }

}



 
   
      
      
      
     
    
   
      
      
      
     
    
   
      
      
      
     
    
   
      
      
      
     
   


你可能感兴趣的:(Java-Dom4J增加、修改xml)