dom4j增删改查

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="b001">
<title>java core</title>
<price>688</price>
</book>
<book id="b002">
<title>思想政治</title>
<price>515</price>
</book>
<book id="b003">
<title id="188888888">世界历史</title>
<price>545</price>
</book>
<book id="b004">
<title>大学生物</title>
<price>512</price>
</book>
</books>


测试类

package com.cgm.dom4jt;

import java.io.FileOutputStream;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jCrud {

/**
* @param args
*/
public static void main(String[] args) {

//读取
SAXReader reader = new SAXReader();
try {
Document document = reader.read("book.xml");

//修改节点
Node bookNode = document.selectSingleNode("//book[@id='b003']");
Element booElement = (Element) bookNode;
Element titleElement = booElement.element("title");
titleElement.setText("三毛的故事");

//删除节点

Node boo2Node = document.selectSingleNode("//book[@id='b002']");
Element booElement2 = (Element) boo2Node;
Node parentNode = boo2Node.getParent();
Element paElement = (Element) parentNode;
paElement.remove(boo2Node);

//增加xml节点

Element rootElement = document.getRootElement();
Element newBook = DocumentHelper.createElement("book");
rootElement.add(newBook);
Attribute idAttribute = DocumentHelper.createAttribute(newBook, "id", "b006");
newBook.add(idAttribute);
//创建下面的标题节点
Element titleElements = DocumentHelper.createElement("title");
titleElements.setText("三国演义");
newBook.add(titleElements);
//创建价格节点
Element priceElement = DocumentHelper.createElement("price");
priceElement.setText("257");
newBook.add(priceElement);

XMLWriter writer = new XMLWriter(new FileOutputStream("books.dom4j.xml"));
writer.write(document);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}

}

}

你可能感兴趣的:(dom4j)