一、前言
基于dom4j源码包基于org.dom4j.io.SAXReader、org.dom4j.io.XMLWriter定义Dom4jHelper解析处理工具类,对XML文档读取parse解析org.dom4j.Document文档、遍历treeWalk解析xml文档、解析文件获得根Element元素、修改xml某节点的值并保存文档,将xml文档toString转为字符串及字符串转换为Document等代码示例。
二、代码示例
package com.xwood.util;@b@@b@import java.io.ByteArrayOutputStream;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileOutputStream;@b@import java.io.FileWriter;@b@import java.io.IOException;@b@import java.io.OutputStreamWriter;@b@import java.net.URL;@b@import java.util.Iterator;@b@import java.util.List;@b@@b@import org.dom4j.Attribute;@b@import org.dom4j.Document;@b@import org.dom4j.DocumentException;@b@import org.dom4j.DocumentHelper;@b@import org.dom4j.Element;@b@import org.dom4j.Node;@b@import org.dom4j.io.OutputFormat;@b@import org.dom4j.io.SAXReader;@b@import org.dom4j.io.XMLWriter;@b@@b@public class Dom4jHelper {@b@ /**@b@ * 解析url xml文档@b@ * @param url@b@ * @return@b@ * @throws DocumentException@b@ */@b@ public static Document parse(URL url) throws DocumentException {@b@ SAXReader reader = new SAXReader();@b@ Document document = reader.read(url);@b@ return document;@b@ }@b@ /**@b@ * 遍历解析文档@b@ * @param document@b@ */@b@ public static void treeWalk(Document document) {@b@ treeWalk( document.getRootElement() );@b@ }@b@ /**@b@ * 遍历解析元素@b@ * @param element@b@ */@b@ public static void treeWalk(Element element) {@b@ for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {@b@ Node node = element.node(i);@b@ if ( node instanceof Element ) {@b@ treeWalk( (Element) node );@b@ }@b@ else {@b@ // 处理....@b@ }@b@ }@b@ }@b@@b@ /** @b@ * 解析文件,获得根元素@b@ * @param xmlPath@b@ * @param encoding@b@ * @return@b@ * @throws Exception@b@ */@b@ public static Element parse(String xmlPath,String encoding)throws Exception{@b@ //文件是否存在@b@ File file = new File(xmlPath);@b@ if(!file.exists()){@b@ throw new Exception("找不到xml文件:"+xmlPath);@b@ }@b@ @b@ //解析@b@ SAXReader reader = new SAXReader(false);@b@ Document doc = reader.read(new FileInputStream(file),encoding);@b@ Element root = doc.getRootElement();@b@ return root;@b@ }@b@ @b@ /**@b@ * 保存文档@b@ * @param doc@b@ * @param xmlPath@b@ * @param encoding@b@ * @throws Exception@b@ */@b@ public static void save(Document doc,String xmlPath,String encoding)throws Exception{@b@ OutputFormat format=OutputFormat.createPrettyPrint();@b@ format.setEncoding(encoding);@b@ XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath),encoding),format);@b@ writer.write(doc);@b@ writer.flush();@b@ writer.close(); @b@ }@b@ /**@b@ * 修改xml某节点的值@b@ * @param inputXml 原xml文件@b@ * @param nodes 要修改的节点@b@ * @param attributename 属性名称@b@ * @param value 新值@b@ * @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件@b@ */@b@ public static void modifyDocument(File inputXml, String nodes, String attributename, String value, String outXml) {@b@ try {@b@ SAXReader saxReader = new SAXReader();@b@ Document document = saxReader.read(inputXml);@b@ List list = document.selectNodes(nodes);@b@ Iterator iter = list.iterator();@b@ while (iter.hasNext()) {@b@ Attribute attribute = (Attribute) iter.next();@b@ if (attribute.getName().equals(attributename))@b@ attribute.setValue(value);@b@ }@b@ XMLWriter output;@b@ if (outXml != null){ //指定输出文件@b@ output = new XMLWriter(new FileWriter(new File(outXml)));@b@ }else{ //输出文件为原文件@b@ output = new XMLWriter(new FileWriter(inputXml));@b@ }@b@ output.write(document);@b@ output.close();@b@ }@b@@b@ catch (DocumentException e) {@b@ System.out.println(e.getMessage());@b@ } catch (IOException e) {@b@ System.out.println(e.getMessage());@b@ }@b@ } @b@ @b@ /**@b@ * xml转换为字符串@b@ * @param doc@b@ * @param encoding@b@ * @return@b@ * @throws Exception@b@ */@b@ public static String toString(Document doc,String encoding)throws Exception{@b@ OutputFormat format=OutputFormat.createPrettyPrint();@b@ format.setEncoding(encoding);@b@ ByteArrayOutputStream byteOS=new ByteArrayOutputStream();@b@ XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS,encoding),format);@b@ writer.write(doc);@b@ writer.flush();@b@ writer.close(); @b@ writer=null;@b@ @b@ return byteOS.toString(encoding);@b@ }@b@ /**@b@ * 字符串转换为Document@b@ * @param text@b@ * @return@b@ * @throws DocumentException@b@ */@b@ public static Document str2Document(String text) throws DocumentException{@b@ Document document = DocumentHelper.parseText(text);@b@ return document;@b@ }@b@ @b@ @b@ public static void main(String[] args) throws Exception{@b@ @b@ Dom4jHelper.parse("C:\\xwood_net\\project\\xwood-project\\JavaTest\\src\\com\\xwood\\util\\config.xml", "utf-8");@b@ @b@ Document xmldoc=Dom4jHelper.parse(new URL("file:///C:/xwood_net/project/xwood-project/JavaTest/src/com/xwood/util/config.xml"));@b@ @b@ System.out.println(Dom4jHelper.toString(xmldoc, "utf-8"));@b@@b@ }@b@@b@}
控制台打印结果如下
<?xml version="1.0" encoding="utf-8"?>@b@@b@<config> @b@ <database> @b@ <url>127.0.0.1</url> @b@ <port>3306</port> @b@ <login>admin</login> @b@ <password/> @b@ </database> @b@</config>