![](https://i-blog.csdnimg.cn/blog_migrate/fa7432c6a0129159367f7c936a447b54.png)
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;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
public class DOM4JDemo {
Document doc = null;
//创建document对象
public void getDocument(){
SAXReader saxReader = new SAXReader();
try {
doc = saxReader.read("src/homework1202/手机收藏.xml");
} catch (DocumentException e) {
e.printStackTrace();
}
}
public void show(){
//获取根元素节点
Element root = doc.getRootElement();
//遍历
for (Iterator itBrand = root.elementIterator();itBrand.hasNext();){
Element brand = (Element) itBrand.next();
System.out.println("品牌:"+brand.attributeValue("name"));
for(Iterator itType = brand.elementIterator();itType.hasNext();){
Element type = (Element) itType.next();
System.out.println("\t型号:"+type.attributeValue("name"));
}
}
}
public void add(){
Element root = doc.getRootElement();
Element brand = root.addElement("Brand");
brand.addAttribute("name","三星");
Element type = brand.addElement("Type");
type.addAttribute("name","note4");
save();
}
public void save(){
try {
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileWriter("src/homework1202/手机收藏.xml"),outputFormat);
writer.write(doc);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void update(){
int id = 1;
Element root = doc.getRootElement();
for (Iterator itBrand = root.elementIterator(); itBrand.hasNext();){
Element element = (Element) itBrand.next();
element.addAttribute("id",id+"");
id++;
}
save();
}
public void delete(){
Element root = doc.getRootElement();
for (Iterator itBrand = root.elementIterator();itBrand.hasNext();){
Element brand = (Element) itBrand.next();
if(brand.attributeValue("name").equals("华为")){
brand.getParent().remove(brand);
}
}
save();
}
public static void main(String[] args) {
DOM4JDemo dom4JDemo = new DOM4JDemo();
dom4JDemo.getDocument();
dom4JDemo.add();
dom4JDemo.update();
dom4JDemo.delete();
dom4JDemo.show();
}
}