常用操作:
添加: 文檔 標簽 屬性
修改: 屬性值,文本內容
刪除: 標簽 屬性
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");
}
}