Dom4j下载地址
链接:https://pan.baidu.com/s/1TYk-ZWVpJymuxE5a7JKmyw
提取码:b604
建立xml文件 phone.xml
<?xml version="1.0" encoding="GBK"?>
<PhoneInfo>
<Brand name="华为">
<Type name="U8650"/>
<Type name="HW123"/>
<Type name="HW321"/>
</Brand>
<Brand name="苹果">
<Type name="iphone8"/>
</Brand>
<Brand name="oppo">
<Type name="oppor17"/>
</Brand>
</PhoneInfo>
导入dm4j.jar包及xml文件
代码实现
package com.offcn.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
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 ConfigUtils {
//测试代码
public static void main(String[] args) {
ConfigUtils configUtils = new ConfigUtils();
configUtils.getDoc("src/phone.xml");
configUtils.add();
configUtils.delete();
configUtils.update();
configUtils.save("src/phone.xml");
configUtils.showInfo();
}
private Document doc;
//获取dom对象
public void getDoc(String path){
SAXReader reader = new SAXReader();
try {
doc = reader.read(new File(path));
} catch (DocumentException e) {
e.printStackTrace();
}
}
//展示所有信息
public void showInfo(){
//获取根元素
Element rootele = doc.getRootElement();
Iterator<?> iterator = rootele.elementIterator();
while(iterator.hasNext()){
Element parentele = (Element)iterator.next();
System.out.println(parentele.attributeValue("name"));
//得到子元素的迭代器
Iterator<?> iterator2 = parentele.elementIterator();
while(iterator2.hasNext()){
Element childele = (Element)iterator2.next();
System.out.println(childele.attributeValue("name"));
}
}
}
//创建一个节点
public void add(){
//得到根节点
Element rootele = doc.getRootElement();
//创建一个elementBrand节点
Element elementBrand = rootele.addElement("Brand");
//设置属性
elementBrand.addAttribute("name", "oppo");
//创建elementType节点
Element elementType = elementBrand.addElement("Type");
//设置属性
elementType.addAttribute("name", "oppor17");
}
//保存到源文件
public void save(String path){
try {
//传入文件路径
FileWriter file = new FileWriter(path);
//格式化
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter writer = new XMLWriter(file,format);
writer.write(doc);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//删除节点
public void delete(){
//获取根元素
Element rootele = doc.getRootElement();
Iterator<?> iterator = rootele.elementIterator();
while(iterator.hasNext()){
Element parentele = (Element)iterator.next();
if(parentele.attributeValue("name").equals("oppor")){
parentele.getParent().remove(parentele);
}
}
}
//更新
public void update(){
//获取根元素
Element rootele = doc.getRootElement();
Iterator<?> iterator = rootele.elementIterator();
int i = 1;
while(iterator.hasNext()){
Element parentele = (Element)iterator.next();
parentele.addAttribute("id", i+1+"");
i++;
}
}
}