dom4j解析
增删改查
src/book.xml
<书架>
<书>
<书名 id="a1" name="shuming">JAVA1</书名>
<作者>张1</作者>
<价格>109</价格>
</书>
<书>
<书名 name="XXXX">JAVA2</书名>
<作者>hhh</作者>
<价格>12(2)</价格>
</书>
</书架>
public class demo5 {
//读取XML文档第二本书的 <书名>JAVA2</书名>
@Test
public void read()throws Exception
{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element root = document.getRootElement();
Element element = (Element) root.elements("书").get(1);
String valueString = element.element("书名").getText();
System.out.println(valueString);
}
//得到第二本书的属性 <书名 name="XXXX">JAVA2</书名>
@Test
public void readAttr()throws Exception
{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element root = document.getRootElement();
Element book = (Element) root.elements("书").get(1);
String valueString = book.element("书名").attributeValue("name");
System.out.println(valueString);
}
//在第一本书上添加一个新的售价<售价>209元</售价>
@Test
public void add() throws Exception
{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element book = document.getRootElement().element("书");
book.addElement("售价").setText("209元");
OutputFormat of = OutputFormat.createPrettyPrint();
of.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter( new FileOutputStream("src/book.xml"),of);
writer.write( document );
writer.close();
}
//在第一本书指定位置添加新的售价<售价>209元</售价> 更改list集合顺序
@Test
public void add2()throws Exception
{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element book = document.getRootElement().element("书");
List<Element> list = book.elements();
Element price =DocumentHelper.createElement("售价");
price.setText("209元");
list.add(2,price);
OutputFormat of = OutputFormat.createPrettyPrint();
of.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter( new FileOutputStream("src/book.xml"),of);
writer.write( document );
writer.close();
}
//删除第一本书的 <售价>209元</售价>
@Test
public void delete()throws Exception
{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element price = document.getRootElement().element("书").element("售价");
price.getParent().remove(price);
OutputFormat of = OutputFormat.createPrettyPrint();
of.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter( new FileOutputStream("src/book.xml"),of);
writer.write( document );
writer.close();
}
//更新第二本书的作者
@Test
public void update() throws Exception
{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml"));
Element book = (Element) document.getRootElement().elements("书").get(1);
book.element("作者").setText("hhh");
OutputFormat of = OutputFormat.createPrettyPrint();
of.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter( new FileOutputStream("src/book.xml"),of);
writer.write( document );
writer.close();
}
}