package edu.dom4j.dom;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class XMLCRUD {
private String xmlfile = "WebRoot/product2.xml";
//取得product2.xml文档的document对象
public Document getDocument() throws DocumentException{
SAXReader reader = new SAXReader();
Document document = reader.read(xmlfile);
return document;
}
//将内存中的document对象写入xml文件中
public Document write2Xml(Document document) throws IOException{
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileOutputStream(xmlfile), format);
writer.write(document);
writer.close();
return document;
}
//在第一个<product>下增加新标签<stock>(加在最后面)
@Test
public void addNewTag() throws DocumentException, IOException{
Document document = getDocument();
Element root = document.getRootElement();
//取得第一个product节点
Element product1 = root.element("product");
//向product1节点中添加一个新节点<stock>
Element stock = product1.addElement("stock")
.addAttribute("description", "库存");
stock.setText("200");
write2Xml(document);
}
//在指定位置插入新标签:在<notes>这是扳手</notes> 前插入<salenum>
@Test
public void insertNewTag() throws DocumentException, IOException{
Document document = getDocument();
//这里创建新节点不能用上面的方式创建新节点了,只能借助于DocumentHelper
Element salenum = DocumentHelper.createElement("salenum");
salenum.addAttribute("description","销量").setText("100");
//取得第一个product节点
Element product1 =document.getRootElement().element("product");
//得到product节点的子节点集合
List<Element> sonList = product1.elements();
sonList.add(2,salenum);
write2Xml(document);
}
//删除指定节点:删除上面插入的<salenum>节点
@Test
public void removeTag() throws DocumentException, IOException{
Document document = getDocument();
Element product1 = document.getRootElement().element("product");
Element salenum = product1.element("salenum");
product1.remove(salenum);
write2Xml(document);
}
//更改<stock description="库存">200</stock> 的属性和Text
@Test
public void updateTag() throws DocumentException, IOException{
Document document = getDocument();
Element product1 = (Element) document.getRootElement().elements("product").get(0);
Element stock = product1.element("stock");
//stock.setAttributeValue("description","库存量");//此方法过时
stock.attribute("description").setValue("库存量");
stock.setText("200件");
write2Xml(document);
}
}
product2.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<catalog id="cata1">
<product category="HandTool" inventory="InStock">
<specifications weight="2.0kg">扳手</specifications>
<price street="香港街">80.0</price>
<notes>这是扳手</notes>
</product>
<product category="Table">
<specifications>桌椅</specifications>
<price street="澳门街" wholesale="部分">100.0</price>
</product>
</catalog>