使用Dom4j 来创建 读取 修改 删除 打印 格式化 XML文档
//加入下面两个包
D:\Soft\jar\dom4j-1.6.1.jar
D:\Soft\jar\jaxen.jar
//开始
package com.itheima.xml;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
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;
public class TextDom4jParseXML {
/**
* @param args
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args) throws IOException, DocumentException {
String filename="F:/test.xml"; //不存在的文件
System.out.println("============1.创建文档");
if (createXMLFile(filename)==1)
System.out.println("创建XML文档成功!");
else
System.out.println("创建XML文件失败!");
System.out.println("=============2.读取XML文件,将文档内容输出到控制台");
read(getDocument(filename));
System.out.println();
System.out.println("=============3.修改XML文档内容,输出修改后的文档内容");
update(filename, "songshu", "liushu");
toControl(filename, getDocument(filename)); //输出修改后的文档,然后保存修改后的文档
System.out.println("============4.删除编号为002的节点,输出删除后的文件");
delete(filename, "002");
toControl(filename, getDocument(filename));
System.out.println("============5.输出节点(/trees/tree)");
print(filename);
System.out.println("============6.格式化文件解决中文问题");
if(formatXML(filename, "GBk")==1){
System.out.println("格式化文档成功!");
}else
System.out.println("格式化失败!");
}
//手动创建一个XML文件 输出到制定的文件下
public static int createXMLFile(String filename){
int returnVale=0; //返回操作的结果 0 表示失败, 1表示成功
//创建XML文件
Document document=DocumentHelper.createDocument();
//创建根节点
Element treesElement=document.addElement("trees");
treesElement.addComment("This is a test for dom4j"); //加入一行注释
//加入 第一个tree节点
Element treeElement=treesElement.addElement("tree");
treeElement.addAttribute("id","001"); //添加id属性内容
treeElement.addAttribute("name", "rongshu"); //添加 name属性内容
Element descElement=treeElement.addElement("description");
descElement.setText("It is a big tree"); //为 descriiption 设置内容
//添加第二个节点
treeElement=treesElement.addElement("tree");
treeElement.addAttribute("id", "002");
treeElement.addAttribute("name", "yangshu");
descElement=treeElement.addElement("description");
descElement.setText("The tree grows taller form day to day");
//添加第三个节点
treeElement=treesElement.addElement("tree");
treeElement.addAttribute("id", "003");
treeElement.addAttribute("name", "songshu");
descElement=treeElement.addElement("description");
descElement.setText("The tree is very beautiful");
Element ownerElement=treesElement.addElement("flower");
ownerElement.setText("rose");
try {
//创建XML文件对象
XMLWriter writer=new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
returnVale=1;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return returnVale;
}
public static void read(Document document) throws IOException{
XMLWriter writer=new XMLWriter(new FileWriter("F:/output.xml"));
writer.write(document);
writer.close();
//将文件内容缩进方式输出到控制台
OutputFormat format=OutputFormat.createPrettyPrint();
writer=new XMLWriter(System.out, format);
writer.write(document);
//讲文件内容紧凑的输出到控制台
format=OutputFormat.createCompactFormat();
writer =new XMLWriter(System.out, format);
writer.write(document);
}
//读取文件获取document
public static Document getDocument(String filename) throws DocumentException{
SAXReader saxReader=new SAXReader();
Document document=saxReader.read(new File(filename));
return document;
}
//删除 XML文件中指定的id节点
public static boolean delete(String filename,String id) throws DocumentException{
boolean returnValue=false;
Document document=getDocument(filename); //调用方法获取document
Element root=document.getRootElement(); //获得根节点
List list=document.selectNodes("/trees/tree/@id"); //获取编号的列表
Iterator iter=list.iterator();
while (iter.hasNext()) {
Attribute attribute=(Attribute)iter.next();
if(attribute.getValue().equals(id)){
Element element=attribute.getParent();
root.remove(element);
}
}
try {
XMLWriter writer=new XMLWriter(new FileOutputStream(new File(filename)));
writer.write(document);
writer.close();
returnValue=true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return returnValue;
}
return returnValue;
}
//修改xml文件中的指定的节点内容 ,并且 添加内容
public static int update(String filename,String oldName,String newName){
int returnValue=0;
try {
Document document=getDocument(filename);
List list=document.selectNodes("/trees/tree/@name");
Iterator iter=list.iterator();
while (iter.hasNext()) {
Attribute attribute = (Attribute)iter.next();
if(attribute.getValue().equals(oldName)){
attribute.setValue(newName);
}
}
list=document.selectNodes("/trees/flower");
iter=list.iterator();
if(iter.hasNext()){
Element flower=(Element)iter.next();
flower.setText("lily");
Element date=flower.addElement("date");
date.setText("2009-04-10");
date.addAttribute("type", "calendar");
}
try {
XMLWriter writer=new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
returnValue=1;
} catch (Exception e) {
// TODO: handle exception
System.out.println("修改XML文件出错:"+e.getMessage());
returnValue=0;
}
} catch (Exception e) {
System.out.println("修改XML文件出错:"+e.getMessage());
returnValue=0;
}
return returnValue;
}
//格式化XML文档并且解决中文乱码
public static int formatXML(String filename,String encoding){
int returnValue=0;
try {
Document document=getDocument(filename);
XMLWriter writer=null;
//格式化输出,类型和ID浏览一样
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding(encoding); //指定XML的编码方式
writer=new XMLWriter(new FileWriter(new File(filename)),format);
writer.write(document);
writer.close();
returnValue=1;
} catch (Exception e) {
System.out.println("格式化XML文档出错:"+e.getMessage());
returnValue=0;
}
return returnValue;
}
public static void toControl(String filename,Document document){
try {
XMLWriter writer=new XMLWriter(new FileWriter(filename));
writer.write(document); //将文档内容输出到文件
writer.close();
//将文档内容格式化输出到控制台
OutputFormat format=OutputFormat.createPrettyPrint();
writer=new XMLWriter(System.out,format);
writer.write(document);
} catch (Exception e) {
// TODO: handle exception
System.out.println("输出出错:"+e.getMessage());
}
}
//将xml转化成String
public static String XmlToString(Document document){
return document.asXML();
}
//将String 转换成 document
public static Document StrintToDocument(String text){
try {
return DocumentHelper.parseText(text);
} catch (Exception e) {
System.out.println("转换出错:"+e.getMessage());
return null;
}
}
//输出节点
public static void print(String filename){
try {
Document doc=getDocument(filename);
Node node=doc.selectSingleNode("/trees/tree");
System.out.println("输出节点:"+node.asXML()); //将节点转化成String
} catch (Exception e) {
// TODO: handle exception
System.out.println("输出节点出错:"+e.getMessage());
}
}
}