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<Element> 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<Element> childList = root.elements();
for(Element element:childList) {
Attribute nameAttribute = element.attribute("name");
if("对公现金来源".equals(nameAttribute.getValue())) {
List<Element> 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();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<item description="" name="对公现金来源">
<item key="01" value="销售货物所得"/>
<item key="02" value="销售货物所得1"/>
<item key="03" value="销售货物所得2"/>
<item key="04" value="销售货物所得3"/>
</item>
<item description="" name="对公现金用途">
<item key="01" value="销售货物所得4"/>
<item key="02" value="销售货物所得5"/>
<item key="03" value="销售货物所得6"/>
<item key="04" value="销售货物所得7"/>
</item>
<item description="" name="对私现金来源">
<item key="01" value="销售货物所得8"/>
<item key="02" value="销售货物所得9"/>
<item key="03" value="销售货物所得10"/>
<item key="04" value="销售货物所得11"/>
</item>
<item description="" name="对私现金用途">
<item key="01" value="销售货物所得12"/>
<item key="02" value="销售货物所得13"/>
<item key="03" value="销售货物所得14"/>
<item key="04" value="销售货物所得15"/>
</item>
</properties>
网友评论