import java.io.File;
import java.io.FileWriter;
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;
SAXReader reader = new SAXReader();
Document document = reader.read(new File("input.xml"));
String text = "<members></members>";
Document document = DocumentHelper.parseText(text);
3.主动创建document对象.
Document document = DocumentHelper.createDocument();
Element root = document.addElement("members");// 创建根节点
二.节点相关
Element rootElm = document.getRootElement();
Element memberElm=root.element("member");// "member"是节点名
String text=memberElm.getText();
也可以用:
List nodes = rootElm.elements("member");
Element elm = (Element) it.next();
// do something
}
for(Iterator it=root.elementIterator();it.hasNext();){
Element element = (Element) it.next();
// do something
}
Element ageElm = newMemberElm.addElement("age");
ageElm.setText("29");
parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点。
三.属性相关
1.取得某节点下的某属性
Element root=document.getRootElement();
Attribute attribute=root.attribute("size");// 属性名name
2.取得属性的文字
String text=attribute.getText();
也可以用:
String text2=root.element("name").attributue("firstname");这个是取得根节点下name字节点的属性firstname的值.
Element root=document.getRootElement();
for(Iterator it=root.attributeIterator();it.hasNext();){
Attribute attribute = (Attribute) it.next();
String text=attribute.getText();
System.out.println(text);
}
4.设置某节点的属性和文字.
newMemberElm.addAttribute("name", "sitinspring");
5.设置属性的文字
Attribute attribute=root.attribute("name");
attribute.setText("sitinspring");
6.删除某属性
Attribute attribute=root.attribute("size");// 属性名name
root.remove(attribute);
四.将文档写入XML文件
1.文档中全为英文,不设置编码,直接写入的形式.
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();
2.文档中含有中文,设置编码格式写入的形式.
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK"); // 指定XML编码
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
writer.write(document);
writer.close();
五.字符串与XML的转换
1.将字符串转化为XML
String text = "<members> <member>sitinspring</member> </members>";
Document document = DocumentHelper.parseText(text);
2.将文档或节点的XML转化为字符串.
SAXReader reader = new SAXReader();
Document document = reader.read(new File("input.xml"));
Element root=document.getRootElement();
String docXmlText=document.asXML();
String rootXmlText=root.asXML();
Element memberElm=root.element("member");
String memberXmlText=memberElm.asXML();
六.使用XPath快速找到节点
读取的XML文档示例
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>MemberManagement</name>
<comment></comment>
<projects>
<project>PRJ1</project>
<project>PRJ2</project>
<project>PRJ3</project>
<project>PRJ4</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
public static void main(String[] args){
SAXReader reader = new SAXReader();
try{
Document doc = reader.read(new File("sample.xml"));
List projects=doc.selectNodes("/projectDescription/projects/project");
Iterator it=projects.iterator();
while(it.hasNext()){
Element elm=(Element)it.next();
System.out.println(elm.getText());
}
}
catch(Exception ex){
ex.printStackTrace();
}
/**
*
* TODO 类
* @Project Name ${project_name}
* @author zhubo(朱波)
* @see mailto:zhubo@inspur.com
* @version 1.0
* @date: 2010-1-30
* XML文件操作封装类:添加元素、修改元素、删除元素、获取某个元素的值
*
* 修改记录:
* 日期 修改人 描述
* -----------------------------------------------------------------------
*/
package com.inspur.plat.platcore.core;
import java.io.File;
import java.io.FileWriter;
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.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlOperator {
private Document document;
private String filePath; //文件所在的实际物理路径
private WriteLog writelog;
public static void main(String[] args) {
String filepath = System.getProperty("user.dir")+"/XmlFiles/LocalServicesConfig.xml";
XmlOperator operator = new XmlOperator(filepath);
operator.getXmlFile();
//operator.addChild("item", "t1","services2", "");
//operator.updateChild("item", "t1", "services2", "bb");
//operator.deleteChild("item", "t1", "services2");
String str = operator.getChild("item", "t3", "protocol");
System.out.println(str);
}
public XmlOperator(String filepath){
this.document = null;
this.filePath = filepath;
writelog = new WriteLog();
}
/**
* 创建XML文件
* @param rootName:根节点名称
*/
public void createXMLFile(String rootName) {
if(!fileExist()){
this.document = DocumentHelper.createDocument();
this.document.addElement(rootName);
saveXMLFile(this.document);
}
}
/**
* 获取已存在的XML文档
* @return
*/
public Document getXmlFile() {
if (fileExist()) {
SAXReader reader = new SAXReader();
try {
this.document = reader.read(new File(filePath));
} catch (DocumentException e) {
String loginfo = StackTraceToString.getExceptionTrace(e);
writelog.writeLogToEnd("LocalServerManager", loginfo);
}finally{
reader = null;
}
} else {
//写日志
String loginfo = "XML file does not exist,read error!";
writelog.writeLogToEnd("LocalServerManager",loginfo);
System.exit(0);
}
return this.document;
}
/**
* 添加元素
* @param fatherPath:父节点名称
* @param fatherattr:父节点属性
* @param childName:要添加的节点名称
* @param childValue:要添加的节点值
*/
public void addChild(String fatherNode, String fatherAttr,String childName, String childValue) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"add");
}
/**
* 修改元素
* @param fatherPath:父节点名称
* @param fatherattr:父节点属性
* @param childName:要修改的节点名称
* @param childValue:要修改成的节点值
*/
public void updateChild(String fatherNode, String fatherAttr,String childName, String childValue) {
ChildOperator(fatherNode,fatherAttr,childName,childValue,"update");
}
/**
* 删除元素
* @param fatherPath:父节点名称
* @param fatherattr:父节点属性
* @param childName:要删除的节点名称
*/
public void deleteChild(String fatherNode, String fatherAttr,String childName) {
ChildOperator(fatherNode,fatherAttr,childName,"","delete");
}
/**
* 获取某个元素数值
* @param fatherPath:父节点名称
* @param fatherattr:父节点属性
* @param childName:要删除的节点名称
*/
public String getChild(String fatherNode, String fatherAttr,String childName) {
String result = "";
result = ChildOperator(fatherNode,fatherAttr,childName,"","get");
return result;
}
/**
* 子节点操作
* @param fatherNode:父节点名称
* @param fatherAttr:父节点属性
* @param childName:要修改的节点
* @param childValue:修改后的节点值
* @param operator: 要执行的操作名称
*/
private synchronized String ChildOperator(String fatherNode, String fatherAttr,String childName, String childValue,String operator) {
String result="";
if (this.document == null) {
//写日志
String loginfo = "Has not get XML file, add err!";
writelog.writeLogToEnd("LocalServerManager",loginfo);
return "null";
}
Element root = this.document.getRootElement();//获取根节点名称
if(!root.getName().equals(fatherNode)){ //如果不是在根节点下添加
result = XmlElementOperator(root,fatherNode,fatherAttr,childName,childValue,operator);
}else{
if(operator.equals("add")){
Element childelement = root.addElement(childName);//根节点不存在元素属性值
childelement.setText(childValue);
saveXMLFile(this.document);
}else if(operator.equals("update")){
List childelements = root.elements(childName);
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
everyone.setText(childValue); //修改该元素值
}
saveXMLFile(this.document);
}else if(operator.equals("delete")){
List childelements = root.elements(childName);//获取当前节点下的所有子节点,判断其值,以进行修改
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
root.remove(everyone);
}
saveXMLFile(this.document);
}else if(operator.equals("get")){
List childelements = root.elements(childName);//获取当前节点下的所有子节点,判断其值,以进行修改
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
result = everyone.getText();
}
saveXMLFile(this.document);
}
}
return result;
}
/**
* 递归元素操作
* @param element:要递归的元素
* @param fatherNode:父节点名称
* @param fatherAttr:父节点属性
* @param childName:要进行操作的节点
* @param childValue:操作后的节点值
* @param operator: 要执行的操作名称
*/
private synchronized String XmlElementOperator(Element element,String fatherNode,String fatherAttr,String childName,String childValue,String operator){
String result = "";
List elements = element.elements();
for(Iterator it=elements.iterator();it.hasNext();){
Element currentelement = (Element)it.next();
if(!currentelement.getName().equals(fatherNode)){ //当前元素并不是我们要查找的父元素时,继续查找
XmlElementOperator(currentelement,fatherNode,fatherAttr,childName,childValue,operator);//递归调用
}else{
if(currentelement.attributeCount()>0){ //当前元素存在属性值时
for(Iterator list=currentelement.attributeIterator();list.hasNext();){ //遍历属性值
Attribute attr = (Attribute)list.next(); //获取属性值队列中的第一个元素
if(attr.getValue().equals(fatherAttr)){//根据属性值确定惟一的父元素
if(operator.equals("add")){//添加元素
Element childelement = currentelement.addElement(childName); //给当前元素添加一个子元素
childelement.setText(childValue); //设置子元素的数值
}else if(operator.equals("update")){//修改某个元素
List childelements = currentelement.elements(childName);//获取当前节点下的所有子节点,判断其值,以进行修改
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
everyone.setText(childValue); //修改该元素值
}
}else if(operator.equals("delete")){ //删除某个指定的元素
List childelements = currentelement.elements(childName);//获取当前节点下的所有子节点,判断其值,以进行修改
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
currentelement.remove(everyone);
}
}else if(operator.equals("get")){
List childelements = currentelement.elements(childName);//获取当前节点下的所有子节点,判断其值,以进行修改
for(Iterator childs=childelements.iterator();childs.hasNext();){
Element everyone = (Element)childs.next();
result = everyone.getText();
}
}
else{
//写日志
String loginfo = "XmlFile Operator not exists!";
writelog.writeLogToEnd("LocalServerManager",loginfo);
}
}
}
}
}
}
saveXMLFile(this.document);
return result;
}
/**
* 保存XML文件
* @param document: XML文件名
*/
private void saveXMLFile(Document document) {
try {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(new FileWriter(new File(filePath)),format);
writer.write(document);
writer.close();
} catch (Exception e) {
String loginfo = StackTraceToString.getExceptionTrace(e);
writelog.writeLogToEnd("LocalServerManager", loginfo);
}
}
/**
* 判断XML文件是否存在.
* @param fileName
* @return
*/
private boolean fileExist() {
java.io.File objFile = new java.io.File(this.filePath);
if (objFile.exists()) {
return true;
} else {
return false;
}
}
}