创建XML文档
XML文件是一种典型的树形文件,每个文档元素都是一个document元素的子节点。而每个子元素都是一个Element对象,对象可以向下包含。
1 因此我们可以通过先创建元素再将元素添加到父元素中,最后将顶层元素添加到根元素中。
2 创建完文档元素后,就可以把元素添加到document对象中,然后写入文件。
主要使用的函数:
Element.setAttribute 为元素添加信息
Element.addContent(String,String) 为元素添加子元素内容,也可以直接添加另一个元素节点
Document.setRootElement(Element) 为文档添加根元素
XMLOutputter.output(Document,FileWriter) 将Docuemnt写入到FileWriter文件流中
@SuppressWarnings("null")2 public static void createXML() {3 // 创建document4 Document mydoc = new Document();56 // 创建元素person17 Element person1 = new Element("person");8 person1.setAttribute("id", "ID001");9 // 添加注释10 person1.addContent(new Comment("this is person1"));1112 person1.addContent(new Element("name").setText("xingoo"));13 person1.addContent(new Element("age").setText("25"));14 person1.addContent(new Element("sex").setText("M"));15 // 可以嵌套添加子元素16 Element address1 = new Element("address");17 address1.setAttribute("zone", "province");18 address1.addContent("LiaoNing");19 person1.addContent(address1);2021 // 创建元素person222 Element person2 = new Element("person");23 person2.setAttribute("id", "ID002");24 // 添加注释25 person2.addContent(new Comment("this is person2"));2627 person2.addContent(new Element("name").setText("xhalo"));28 person2.addContent(new Element("age").setText("26"));29 person2.addContent(new Element("sex").setText("M"));30 // 可以嵌套添加子元素31 Element address2 = new Element("address");32 address2.setAttribute("zone", "province");33 address2.addContent("JiLin");34 person2.addContent(address2);3536 // 在doc中添加元素Person37 Element info = new Element("information");38 info.addContent(person1);39 info.addContent(person2);40 mydoc.setRootElement(info);4142 saveXML(mydoc);43 }saveXML()代码:1 public static void saveXML(Document doc) {2 // 将doc对象输出到文件3 try {4 // 创建xml文件输出流5 XMLOutputter xmlopt = new XMLOutputter();67 // 创建文件输出流8 FileWriter writer = new FileWriter("person.xml");910 // 指定文档格式11 Format fm = Format.getPrettyFormat();12 // fm.setEncoding("GB2312");13 xmlopt.setFormat(fm);1415 // 将doc写入到指定的文件中16 xmlopt.output(doc, writer);17 writer.close();18 } catch (Exception e) {19 e.printStackTrace();20 }21 }
执行后,刷新项目,就可以在项目下看到person.xml文件了
修改同理
删除 :
public static void removeXML() {SAXBuilder sb = new SAXBuilder();Document doc = null;try {doc = sb.build("person.xml");Element root = doc.getRootElement();List<Element> list = root.getChildren("person");for (Element el : list) {if (el.getAttributeValue("id").equals("ID001")) {root.removeContent(el);}}} catch (Exception e) {e.printStackTrace();}saveXML(doc);}