常用操作:
添加: 文档 标签 属性
修改: 属性值,文本内容
删除: 标签 属性
public class Demo3 {
public static void main(String[] args) throws Exception {
//add();
//edit();
//-----删除:
Document doc = new SAXReader().read(new File("./src/contact.xml"));
Element conElem = doc.getRootElement().element("contact");
//conElem.detach(); //自杀
//conElem.getParent().remove(conElem); //他杀
//-> 删除属性
Attribute idAttr = doc.getRootElement().element("contact").attribute("id");
idAttr.detach();
//:-----把文档写出到xml文件中
OutputStream out = new FileOutputStream("e:/contact.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
/*1.设置了xml文件的编码
*2.设置了xml文件保存时的编码*/
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
}
private static void edit() throws DocumentException, FileNotFoundException,
UnsupportedEncodingException, IOException {
Document doc = new SAXReader().read(new File("./src/contact.xml"));
//------修改属性
//-> 先得到属性对象,再调用方法修改属性值
/*Element conElem = doc.getRootElement().element("contact");
Attribute idAttr = conElem.attribute("id");
idAttr.setValue("003");*/
//->在标签中添加同名的属性,覆盖属性值
Element conElem = doc.getRootElement().element("contact");
conElem.addAttribute("id", "004");
//->修改文本
Element nameElem = doc.getRootElement().element("contact").element("name");
nameElem.setText("王五");
}
private static void add() throws FileNotFoundException,
UnsupportedEncodingException, IOException {
//:-----添加
//-> 添加空文档
Document doc = DocumentHelper.createDocument();
//-> 添加标签
Element conListElem = doc.addElement("contact-list");
//doc.addElement("contact-list"); //不能添加两个根标签!!!
Element conElem = conListElem.addElement("contact");
conElem.addElement("name");
//-> 添加属性
conElem.addAttribute("id", "001");
conElem.addAttribute("name","eric");
}
}