dom4j解析xml文档&保存数据的乱码问题

 package itcast.dom4j;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException; import org.dom4j.Document;
import org.dom4j.DocumentException;
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 Demo { //读取xml文档第二本书的:<bookname>XXXX</bookname>
@Test
public void read() 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 value = book.element("bookname").getText(); System.out.println(value);
} @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 value = book.element("bookname").attributeValue("name"); System.out.println(value);
} //在第一本书上添加一个新的售价:<price>209yuan</price>
@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("price").setText("209yuan"); OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
writer.write(document);
writer.close();
} }
 <?xml version="1.0" encoding="UTF-8"?>

 <书架>
<书>
<bookname name="zero">java jiuyepeixunjiaocheng</bookname>
<editor>zhangxiaoxiang</editor>
<price>109yuan</price>
<price>209yuan</price>
<price>209yuan</price>
</书>
<书>
<bookname name="one">javaWebprogramming</bookname>
<editor>lihuoming</editor>
<price>28.00yuan</price>
</书>
</书架>
上一篇:SQL Server 用链接服务器 同步MySQL


下一篇:数据库事务的四个特性(ACID)、事务的隔离级别