//XML文件
<?xml version="1.0" encoding="gb2312"?>
<PhoneInfo>
<Brand name="华为" ID="1">
<Type name="P9">
<title>标题信息</title>
</Type>
</Brand>
<Brand name="苹果" ID="2">
<Type name="inphone6"/>
<Type name="inphone7">
<title>标题信息</title>
</Type>
</Brand>
</PhoneInfo>
public class DOM4jParse {
Document doc=null;
//创建Document对象的方法
public void creatInfo() throws DocumentException{
SAXReader reader=new SAXReader();
doc = reader.read(new File("src/Phone.xml"));
}
//遍历XML文件信息的 方法
public void showInfo(){
//获得根元素
Element rootElement = doc.getRootElement();
Iterator iterator = rootElement.elementIterator();
while (iterator.hasNext()) {
Element brandElement=(Element)iterator.next();
//取得brand 属性name的值
String value = brandElement.attributeValue("name");
Iterator elementType = brandElement.elementIterator();
while (elementType.hasNext()) {
Element typeElement=(Element)elementType.next();
//取得Type属性 name的值
String typeName = typeElement.attributeValue("name");
//取得typeElement子节点的文字
String title = typeElement.elementText("title");
System.out.println(value+typeName+title);
}
}
}
//保存文件的方法
public void saveInfo(String path) throws IOException{
OutputFormat fomat=OutputFormat.createPrettyPrint();
fomat.setEncoding("gb2312");
XMLWriter writer=new XMLWriter(new FileWriter(path),fomat);
writer.write(doc);
writer.close();
}
//增加节点信息 (三星 Note4"标题信息")
public void addInfo() throws IOException{
//找到根节点
Element rootElement = doc.getRootElement();
//创建一个Brand节点
Element brandElement = rootElement.addElement("Brand");
brandElement.addAttribute("name", "三星");
Element type = brandElement.addElement("Type");
type.addAttribute("name", "Note4");
Element title =type.addElement("title");
title.setText("标题信息");
this.saveInfo("src/Phone.xml");
}
//修改XML信息
public void changeInfo() throws IOException{
Element rootElement = doc.getRootElement();
int id=0;
Iterator brandElement = rootElement.elementIterator();
while (brandElement.hasNext()) {
id++;
Element brand=(Element)brandElement.next();
brand.addAttribute("ID", id+"");
}
this.saveInfo("src/Phone.xml");
}
//删除XML信息的方法
public void deleInfo() throws IOException{
Element rootElement = doc.getRootElement();
Iterator elementIterator = rootElement.elementIterator();
while (elementIterator.hasNext()) {
Element brand=(Element)elementIterator.next();
String value = brand.attributeValue("name");
if (value.equals("三星")) {
brand.getParent().remove(brand);
}
}
this.saveInfo("src/Phone.xml");
}
/**
* DOM4j(解析,添加,删除,修改,保存文件)XML方法
* @param args
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args) throws DocumentException, IOException {
DOM4jParse d=new DOM4jParse();
d.creatInfo();
//d.addInfo();
//d.changeInfo();
d.deleInfo();
d.showInfo();
}
}