dom4jを使ってxmlを作成、更新、削除するサンプルコード

1.作成(create)
private static void create() throws Exception {
Document document = DocumentHelper.createDocument();
Element student = DocumentHelper.createElement(“student");
document.add(student);
Element name = student.addElement(“name").addAttribute(“a", “x").addText(“welcom");
Element age = student.addElement(“age").addText(“30");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(“utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(“output.xml"),format);
writer.write(document);
writer.close();
}

2.挿入(insert)
private static void insert(Document document) throws Exception {
Element root = document.getRootElement();
List list = root.elements(“student");
Element student = (Element)list.get(1);
Element tmpElement = student.addElement(“tmpChild");
tmpElement.setText(“tmp"); //タグ追加
tmpElement.addAttribute(“tmpname", “tmpvalue"); //属性追加
Element tmp2 = DocumentHelper.createElement(“tmpChild2");//element作成
tmp2.setText(“tmp2");
list.add(1,tmp2);
XMLWriter writer = new XMLWriter(new FileOutputStream(“atdemo.xml"));
writer.write(document);
writer.close();
}

3.ドキュメントを読み込む(Read)
private static void read(Document document) throws Exception{
Element root = document.getRootElement();
Element student = (Element) root.elements(“student").get(1);
String value = student.element(“name").getText();
String attri = student.element(“name").attributeValue(“a");
System.out.println(value);
System.out.println(attri);
}
4.ドキュメント更新(Update)
private static void update(Document document) throws Exception{
Element root = document.getRootElement();
Element name = root.element(“student").element(“name");
name.setText(“this is a message"); //tag更新
name.attribute(“a").setValue(“bb"); //属性更新
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(“utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(“liuga.xml"),format);
writer.write(document);
writer.close();
}

5.ドキュメント削除(delete)
private static void delete(Document document) throws Exception {
Element root = document.getRootElement();
Element name = root.element(“student").element(“name");
name.remove(name.attribute(“a")); //attribute削除
name.getParent().remove(name); //element削除
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(“utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(“soba.xml"),format);
writer.write(document);
writer.close();
}

Java

Posted by arkgame