XML解析方式分为两种:
DOM方式:Document Object Model,文档对象模型。这种方式是W3C推荐的处理XML的一种方式。
SAX:Simple API for XML。这种方式不是官方标准,属于开源社区XML-DEV,几乎所有的XML解析器都支持它。
XML解析开发包
JAXP:是SUN公司推出的解析标准实现。JDK
Dom4J:是开源组织推出的解析开发包。(牛,大家都在用,包括SUN公司的一些技术的实现都在用)
JDom:是开源组织推出的解析开发包。
DOM方式解析XML
exam.xml如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><exam>
<student examid="222" idcard="111">
<name>张三</name>
<location>沈阳</location>
<grade>89</grade>
</student>
<student examid="444" idcard="333">
<name>李四</name>
<location>大连</location>
<grade>97</grade>
</student>
</exam>
com.it.domain包下的Student.java
JavaBean:数据传送对象
package com.itheima.domain;
//代表学生信息的JavaBean
public class Student {
private String idcard;//身份证号码
private String examid;//准考证号
private String name;
private String location;
private float grade;
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getExamid() {
return examid;
}
public void setExamid(String examid) {
this.examid = examid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
@Override
public String toString(){
return "姓名:"+name+"\t身份证号:"+idcard+"\t准考证号:"
+examid+"\t地址:"+location+"\t成绩:"+grade;
}
}
com.it.utils包下的XmlUtil.java
工具栏类:1)提供Document对象
2 )更新XML文档
package com.itheima.utils;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
/**
* 工具类
* 功能:
* 1,获取Document对象
* 2,更新XML
* @author Administrator
*
*/
public class XmlUtil {
//得到Document对象
public static Document getDocument() throws Exception{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse("src/exam.xml");
return document;
}
//更新xml
public static void write2xml(Document document)throws Exception{
Transformer ts = TransformerFactory.newInstance().newTransformer();
ts.transform(new DOMSource(document), new StreamResult("src/exam.xml"));
}
}
com.it.dao包下的StudentDAO.java
DAO:Data Access Object数据访问对象,进行增删改查
package com.itheima.dao;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.itheima.domain.Student;
import com.itheima.utils.XmlUtil;
//完成xml文档的查询,删除,添加操作
public class StudentDAO {
public boolean addStudent(Student student){
boolean result = false;
try{
//1,得到Document对象
Document document = XmlUtil.getDocument();
//2,创建学生节点,设置属性<student idcard="333" examid="444">
Element studentE = document.createElement("student");
studentE.setAttribute("idcard",student.getIdcard());
studentE.setAttribute("examid", student.getExamid());
//3,创建name节点,并设置其内容<name>李四</name>
Element nameE = document.createElement("name");
nameE.setTextContent(student.getName());
//4,创建location节点,并设置其内容<location>大连</location>
Element locationE = document.createElement("location");
locationE.setTextContent(student.getLocation());
//5,创建grade节点,并设置其内容<grade>97</grade>
Element gradeE = document.createElement("grade");
gradeE.setTextContent(student.getGrade()+"");
//6,建立关系
studentE.appendChild(nameE);
studentE.appendChild(locationE);
studentE.appendChild(gradeE);
document.getElementsByTagName("exam").item(0).appendChild(studentE);
//7,更新xml
XmlUtil.write2xml(document);
result = true;
}catch (Exception e){
throw new RuntimeException(e);//异常转移:受检查异常--->运行时异常
//保持异常链e
}
return result;
}
public boolean removeStudent(String name){
boolean result = false;
try{
//1,得到Document对象
Document document = XmlUtil.getDocument();
//2,得到name节点
NodeList list = document.getElementsByTagName("name");
//3,循环遍历所有的name节点,比对主体内容与参数是否匹配
for(int i = 0; i<list.getLength(); i++){
Node node = list.item(i);
if(node.getTextContent().equals(name.trim())){
//4,如果是,得到爷爷删除爸爸
node.getParentNode().getParentNode().removeChild(node.getParentNode());
//5,更新xml
XmlUtil.write2xml(document);
result = true;
}
}
}catch(Exception e){
throw new RuntimeException(e);//异常转移:受检查异常--->运行时异常
//保持异常链e
}
return result;
}
public Student queryStudent(String examid) {
Student student = null;
try{
//1,得到所有的student元素
Document document = XmlUtil.getDocument();
NodeList list = document.getElementsByTagName("student");
//2,循环遍历,判断examid的取值是否与参数匹配
for(int i = 0; i<list.getLength(); i++){
Node node = list.item(i);
Element e = (Element) node;;
if(e.getAttribute("examid").equals(examid.trim())){
//3,如果匹配,创建student对象
student = new Student();
//4,获取数据,并封装到student对象中
student.setExamid(examid);
student.setIdcard(e.getAttribute("idcard"));
student.setName(e.getElementsByTagName("name").item(0).getTextContent());
student.setLocation(e.getElementsByTagName("location").item(0).getTextContent());
student.setGrade(Float.parseFloat(e.getElementsByTagName("grade").item(0).getTextContent()));
}
}
}catch(Exception e){
throw new RuntimeException(e);//异常转移:受检查异常--->运行时异常
//保持异常链e
}
return student;
}
}
com.it.ui包下的main.java
UI:基于控制台的操作界面
package com.itheima.ui;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.itheima.dao.StudentDAO;
import com.itheima.domain.Student;
public class Main {
public static void main(String[] args) {
// 1,打印操作提示
System.out.println("a,添加学生\tb,删除学生\tb,查询学生");
System.out.println("请输入操作类型:");
//2,接受用户的输入
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String operator = br.readLine();
StudentDAO dao = new StudentDAO();
//3,对用户输入的内容进行判断
if("a".equals(operator)){
//添加操作
System.out.println("请输入学生姓名:");
String name = br.readLine();
System.out.println("请输入学生准考证号:");
String examid = br.readLine();
System.out.println("请输入学生身份证号:");
String idcard = br.readLine();
System.out.println("请输入学生地址:");
String location = br.readLine();
System.out.println("请输入学生成绩:");
String grade = br.readLine();
Student student = new Student();
student.setExamid(examid);
student.setGrade(Float.parseFloat(grade));
student.setIdcard(idcard);
student.setLocation(location);
student.setName(name);
boolean result = dao.addStudent(student);
if(result){
System.out.println("-----添加成功------");
}
else{
System.out.println("-----添加失败------");
}
}
else if("b".equals(operator)){
//删除
System.out.println("请输入要删除的学生姓名:");
String name = br.readLine();
boolean result = dao.removeStudent(name);
if(result){
System.out.println("-----删除成功------");
}else{
System.out.println("-----删除失败或者学生不存在------");
}
}
else if("c".equals(operator)){
//查询
System.out.println("请输入要查询的学生准考证号:");
String examid = br.readLine();
Student s = dao.queryStudent(examid);
if(s == null){
System.out.println("学生不存在");
}
else{
System.out.println(s.toString());
}
}
else{
System.out.println("你火星来的吗");
}
}catch(Exception e){
System.out.println("程序忙,请重新启动");
}
}
}
SAX方式解析XML
package day02;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class SaxDemo1 {
public static void main(String[] args) throws Exception{
//1,得到解析器
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
//2,得到读取器
XMLReader reader = sp.getXMLReader();
//reader.setContentHandler(new MyContentHandler());//注册事件处理器
//reader.setContentHandler(new MyContentHandler1());//注册事件处理器
reader.setContentHandler(new DefaultHandler(){//匿名内部类
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了开始标签:"+qName);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了结束标签:"+qName);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了主体内容"+new String(ch,start,length));
}
});//注册事件处理器
reader.parse("src/book.xml");
//3,编写事件处理器
}
}
class MyContentHandler1 extends DefaultHandler{//默认适配器
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了开始标签:"+qName);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了结束标签:"+qName);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了主体内容"+new String(ch,start,length));
}
}
class MyContentHandler implements ContentHandler{
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了开始标签:"+qName);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了结束标签:"+qName);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
System.out.println("当前解析到了主体内容"+new String(ch,start,length));
}
@Override
public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void processingInstruction(String target, String data)
throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void skippedEntity(String name) throws SAXException {
// TODO Auto-generated method stub
}
}
package day02;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
//得到第二本书的售价主体内容
public class SAXDemo2 {
public static void main(String[] args) throws Exception{
//1,得到解析器
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
//2,得到读取器
XMLReader reader = sp.getXMLReader();
//3,为读取器注册事件监听器
reader.setContentHandler(new DefaultHandler(){
int index = 0;
boolean isPrice = false;
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
if("售价".equals(qName)){
isPrice = true;
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if("售价".equals(qName)){
isPrice = false;
index++;
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(index == 1 && isPrice){
System.out.println(new String(ch,start,length));
}
}
});
//4,读取xml
reader.parse("src/book.xml");
}
}
package day02;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
//采用SAX方式解析xml文档,并把得到的内容封装到bean book.java
public class SAXDemo3 {
public static void main(String[] args) throws Exception{
SAXParser sp = SAXParserFactory.newInstance().newSAXParser();
//2,得到读取器
XMLReader reader = sp.getXMLReader();
//3,为读取器注册事件监听器
BeanHandler bh = new BeanHandler();
reader.setContentHandler(bh);
reader.parse("src/book.xml");
//System.out.println(bh.getBooks().size());
for(Book b:bh.getBooks()){
System.out.println(b);
}
}
}
class BeanHandler extends DefaultHandler{
private List<Book> books = new ArrayList<Book>();
Book book = null;
String currentTagName = null;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentTagName = qName;
if(qName.equals("书")){
book = new Book();
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if("书名".equals(currentTagName)){
book.setName(new String(ch,start,length));
}
if("作者".equals(currentTagName)){
book.setAuthor(new String(ch,start,length));
}
if("售价".equals(currentTagName)){
book.setPrice(new String(ch,start,length));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentTagName = null;
if(qName.equals("书")){
books.add(book);
}
}
public List<Book> getBooks() {
return books;
}
}
使用JAXP进行DOM解析
package com.itheima;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
//DOM方式解析XML
public class JaxpCRUD {
public static void main(String[] args) throws Exception {
//1、得到解析器 DocumentBuilder
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//alt+/
DocumentBuilder db = dbf.newDocumentBuilder();//ctrl+1
//2、得到代表整个XML文档的Document对象
Document document = db.parse("src/book.xml");
//test1(document);
//test2(document);
//test3(document);
//test4(document);
//test5(document);
//test6(document);//ctrl+shift+c //
test7(document);//ctrl+shift+c //
test8(document);//ctrl+alt+方向键 复制
}
//1、得到某个具体的节点的内容:第二本书的售价
private static void test1(Document document){
NodeList list = document.getElementsByTagName("售价");
//System.out.println(list.getLength());
Node node = list.item(1);
System.out.println(node.getTextContent());
}
//2、遍历所有元素节点:递归
private static void test2(Node node){
//1,首先判断Node是否是元素节点,如果是,打印该节点名称
if(node.getNodeType() == Node.ELEMENT_NODE){
System.out.println(node.getNodeName());
}
//2,判断是否有孩子节点,循环遍历
NodeList childNode = node.getChildNodes();
for(int i = 0; i< childNode.getLength(); i++)
{
Node n = childNode.item(i);
test2(n);//3,递归调用
}
}
//3,修改某个节点的主体内容:第一本书的售价改为100
private static void test3(Document document) throws Exception{
//1,得到第一本书的售价节点
Node node = document.getElementsByTagName("售价").item(0);
//2,修改主体内容
node.setTextContent("100.0元");
System.out.println(node.getTextContent());
//3,更新xml
//3.1 利用Transformer的transform更新文档
//3.2 得到transformer对象
TransformerFactory tf = TransformerFactory.newInstance();
Transformer ts = tf.newTransformer();
ts.transform(new DOMSource(document), new StreamResult("src/book.xml"));
}
//向指定元素节点中增加子元素节点
//为第一本书增加一个新节点<批发价>58</批发价>
private static void test4(Document document) throws Exception{
//1 得到第一本书的节点
Node bookNode = document.getElementsByTagName("书").item(0);
//2,创建新节点,并设置主体内容
Element newElm = document.createElement("批发价");
newElm.setTextContent("58.00");
//3,建立与书的关系
bookNode.appendChild(newElm);
//4,更新xml
TransformerFactory tf = TransformerFactory.newInstance();
Transformer ts = tf.newTransformer();
ts.transform(new DOMSource(document), new StreamResult("src/book.xml"));
}
//向指定元素节点上增加同济元素节点
//在第一个《售价》前面增加
private static void test5(Document document)throws Exception{
//1,找到第一个 售价节点
Node node = document.getElementsByTagName("售价").item(0);
//2,创建新节点<内部价>10.00</内部价>
Element e = document.createElement("内部价");
e.setTextContent("10.00");
//3,由父节点完成插入操作
node.getParentNode().insertBefore(e, node);
//4,更新xml
TransformerFactory tf = TransformerFactory.newInstance();
Transformer ts = tf.newTransformer();
ts.transform(new DOMSource(document), new StreamResult("src/book.xml"));
}
//删除指定元素节点
private static void test6(Document document)throws Exception{
//得到内部节点
Node node = document.getElementsByTagName("内部价").item(0);
//用他爸爸删除他
Node pre = node.getParentNode();
pre.removeChild(node);
//4,更新xml
TransformerFactory tf = TransformerFactory.newInstance();
Transformer ts = tf.newTransformer();
ts.transform(new DOMSource(document), new StreamResult("src/book.xml"));
}
//得到出版社的值
private static void test7(Document document)throws Exception{
Node node = document.getElementsByTagName("书").item(0);
if(node.getNodeType() == Node.ELEMENT_NODE){
Element e = (Element)node;
System.out.print(e.getAttribute("出版社"));
}
}
//<书 出版社="123"></书>
private static void test8(Document document)throws Exception{
Node node = document.getElementsByTagName("书").item(1);
//2,设置属性
if(node.getNodeType() == Node.ELEMENT_NODE){
Element e = (Element)node;
e.setAttribute("出版社", "123");
}
//3,更新xml
TransformerFactory tf = TransformerFactory.newInstance();
Transformer ts = tf.newTransformer();
ts.transform(new DOMSource(document), new StreamResult("src/book.xml"));
}
}
Dom4J实现解析XML
book.xml
<?xml version="1.0" encoding="UTF-8"?>
<书架>
<书 出版社="黑马">
<书名>Java就业培训教程</书名>
<作者>张孝祥1</作者>
<内部价>10</内部价>
<售价>39.00元</售价>
<批发价>58.00</批发价>
<内部价>60</内部价>
</书>
<书 出版社="123">
<书名>JavaScript</书名>
<售价>28.00元</售价>
</书>
</书架>
package dom4j;
import java.io.FileOutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Assert;
import org.junit.Test;
public class dom4jDemo {
//1,得到某个具体的节点内容
//得到第二本书的主体内容
@Test
public void test1() throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
//4得到第二本书的元素
Element book = (Element)root.elements("书").get(1);
Element name = book.element("书名");
Assert.assertEquals("JavaScript", name.getText());
}
//2,遍历所有元素节点,打印元素的名称
@Test
public void test2()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
treeWalk(root);
}
public void treeWalk(Element element){
//直接打印他的名字
System.out.println(element.getName());
//获取其孩子,循环遍历
int count = element.nodeCount();
for(int i = 0; i<count; i++){
Node node = element.node(i);
//判断node是否是元素
if(node.getNodeType() == Node.ELEMENT_NODE){
treeWalk((Element)node);
}
}
}
//3,修改某个元素节点的主体内容
//更改第二本书的作者为aaa
@Test
public void test3()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
//4,得到第二本书的作者
Element book = (Element)root.elements("书").get(1);
Element author = book.element("作者");
//5,设置其内容
author.setText("aaa");
//6,更新xml文档
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");//设置编码
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
//默认编码就是UTF-8
writer.write(document);
writer.close();
}
//4,向指定元素节点中增加子元素节点
//向第一本书中增加一个新节点叫<内部价>60</内部价>
@Test
public void test4()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
//4,得到第一本书
Element book = root.element("书");
Element price = DocumentHelper.createElement("内部价");
price.setText("60");
book.add(price);
//6,更新xml文档
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");//设置编码
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
//默认编码就是UTF-8
writer.write(document);
writer.close();
}
//5,向指定元素节点上增加同级元素节点
//向第一本书的售价前面增加批发价
@Test
public void test5()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
List list = root.element("书").elements();
Element price = DocumentHelper.createElement("内部价");
price.setText("10");
list.add(2, price);
//6,更新xml文档
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");//设置编码
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
//默认编码就是UTF-8
writer.write(document);
writer.close();
}
//6,删除指定元素节点
//删除第二本的作者
@Test
public void test6()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
Element book = (Element)root.elements("书").get(1);
Element author = book.element("作者");
author.getParent().remove(author);
//6,更新xml文档
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");//设置编码
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
//默认编码就是UTF-8
writer.write(document);
writer.close();
}
//7,操作XML文件属性
@Test
public void test7()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
//3,获取跟元素
Element root = document.getRootElement();
Element book = (Element)root.elements("书").get(1);
Assert.assertEquals("123", book.attributeValue("出版社"));
}
//8,将XML文档转换为String
@Test
public void test8()throws Exception{
//1,得到解析器 xpath
SAXReader reader = new SAXReader();
//2,加载xml文档
Document document = reader.read("src/book.xml");
String text = document.asXML();
System.out.println(text);
}
//8,将XML文档转换为String
@Test
public void test9()throws Exception{
String text = "<person><name>James</name></person>";
Document document = DocumentHelper.parseText(text);
//6,更新xml文档
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");//设置编码
XMLWriter writer = new XMLWriter(new FileOutputStream("D:/book1.xml"),format);
//默认编码就是UTF-8
writer.write(document);
writer.close();
}
}