import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
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 Dom4jHelper {
/**
* 解析url xml文档
* @param url
* @return
* @throws DocumentException
*/
public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
/**
* 遍历解析文档
* @param document
*/
public void treeWalk(Document document) {
treeWalk( document.getRootElement() );
}
/**
* 遍历解析元素
* @param element
*/
public void treeWalk(Element element) {
for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
Node node = element.node(i);
if ( node instanceof Element ) {
treeWalk( (Element) node );
}
else {
// 处理....
}
}
} /**
* 解析文件,获得根元素
* @param xmlPath
* @param encoding
* @return
* @throws Exception
*/
public static Element parse(String xmlPath,String encoding)throws Exception{
//文件是否存在
File file = new File(xmlPath);
if(!file.exists()){
throw new Exception("找不到xml文件:"+xmlPath);
} //解析
SAXReader reader = new SAXReader(false);
Document doc = reader.read(new FileInputStream(file),encoding);
Element root = doc.getRootElement();
return root;
} /**
* 保存文档
* @param doc
* @param xmlPath
* @param encoding
* @throws Exception
*/
public static void save(Document doc,String xmlPath,String encoding)throws Exception{
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath),encoding),format);
writer.write(doc);
writer.flush();
writer.close();
}
/**
* 修改xml某节点的值
* @param inputXml 原xml文件
* @param nodes 要修改的节点
* @param attributename 属性名称
* @param value 新值
* @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件
*/
public static void modifyDocument(File inputXml, String nodes, String attributename, String value, String outXml) {
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
List list = document.selectNodes(nodes);
Iterator iter = list.iterator();
while (iter.hasNext()) {
Attribute attribute = (Attribute) iter.next();
if (attribute.getName().equals(attributename))
attribute.setValue(value);
}
XMLWriter output;
if (outXml != null){ //指定输出文件
output = new XMLWriter(new FileWriter(new File(outXml)));
}else{ //输出文件为原文件
output = new XMLWriter(new FileWriter(inputXml));
}
output.write(document);
output.close();
} catch (DocumentException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
} /**
* xml转换为字符串
* @param doc
* @param encoding
* @return
* @throws Exception
*/
public static String toString(Document doc,String encoding)throws Exception{
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
ByteArrayOutputStream byteOS=new ByteArrayOutputStream();
XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS,encoding),format);
writer.write(doc);
writer.flush();
writer.close();
writer=null; return byteOS.toString(encoding);
}
/**
* 字符串转换为Document
* @param text
* @return
* @throws DocumentException
*/
public static Document str2Document(String text) throws DocumentException{
Document document = DocumentHelper.parseText(text);
return document;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub } }

Java-Dom4jHelper工具类的更多相关文章

  1. Java Properties工具类详解

    1.Java Properties工具类位于java.util.Properties,该工具类的使用极其简单方便.首先该类是继承自 Hashtable<Object,Object> 这就奠 ...

  2. Java json工具类,jackson工具类,ObjectMapper工具类

    Java json工具类,jackson工具类,ObjectMapper工具类 >>>>>>>>>>>>>>> ...

  3. Java日期工具类,Java时间工具类,Java时间格式化

    Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...

  4. Java并发工具类 - CountDownLatch

    Java并发工具类 - CountDownLatch 1.简介 CountDownLatch是Java1.5之后引入的Java并发工具类,放在java.util.concurrent包下面 http: ...

  5. MinerUtil.java 爬虫工具类

    MinerUtil.java 爬虫工具类 package com.iteye.injavawetrust.miner; import java.io.File; import java.io.File ...

  6. MinerDB.java 数据库工具类

    MinerDB.java 数据库工具类 package com.iteye.injavawetrust.miner; import java.sql.Connection; import java.s ...

  7. 小记Java时间工具类

    小记Java时间工具类 废话不多说,这里主要记录以下几个工具 两个时间只差(Data) 获取时间的格式 格式化时间 返回String 两个时间只差(String) 获取两个时间之间的日期.月份.年份 ...

  8. Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie

    Java Cookie工具类,Java CookieUtils 工具类,Java如何增加Cookie >>>>>>>>>>>>& ...

  9. UrlUtils工具类,Java URL工具类,Java URL链接工具类

    UrlUtils工具类,Java URL工具类,Java URL链接工具类 >>>>>>>>>>>>>>>&g ...

  10. java日期工具类DateUtil-续一

    上篇文章中,我为大家分享了下DateUtil第一版源码,但就如同文章中所说,我发现了还存在不完善的地方,所以我又做了优化和扩展. 更新日志: 1.修正当字符串日期风格为MM-dd或yyyy-MM时,若 ...

随机推荐

  1. [bzoj3193][JLOI2013]地形生成_排列组合_贪心

    [JLOI2013]地形生成 题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=3193 题解: 这种求总排列的题,一种常规做法就是所有的元素 ...

  2. springBoot整合Listener

    新建项目 这个是pom文件 <properties> <java.version>1.8</java.version> </properties> &l ...

  3. [转帖]方正数码发布基于龙芯3A3000系列整机

    方正数码发布基于龙芯3A3000系列整机 http://www.loongson.cn/news/company/730.html 方正数码也出过龙芯相关的服务器和PC笔记本等 发布时间:2019-0 ...

  4. Linux系列(4):入门之文件权限与目录配置

    众所周知,Linux是多用户多任务的操作系统.那么如何解决自己文件不被其他用户访问呢?这就需要引入权限管理了. Linux根据文件的所属者分为3个类别:owner.group.others,且每个类别 ...

  5. python的异常处理机制

    异常机制己经成为衡量一门编程语言是否成熟的标准之一,使用异常处理机制的 Python 程序有更好的容错性,更加健壮. 对于计算机程序而言,情况就更复杂了一一没有人能保证自己写的程序永远不会出辛苦!就算 ...

  6. javascript的一些有用函数记录,不断更新。。。

    addLoadEvent函数: 众所周知,html文档加载完后会立即执行一个onload函数.但是onload函数只能包含一个被执行的函数,也就是你需要在加载完文档后执行的一个自己的函数.在实际中ht ...

  7. SDL2 程序 编译 错误 及 解决方案

    main函数应写为int main( int argc, char* args[] )而不是int main()形式 链接库时应注意顺序 mingw32;SDL2main;SDL2;          ...

  8. sort()方法的用法,参数以及排序原理

    sort() 方法用于对数组的元素进行排序,并返回数组.默认排序顺序是根据字符串Unicode码点.语法:arrayObject.sort(sortby):参数sortby可选.规定排序顺序.必须是函 ...

  9. Ubuntu下安卓模拟器的选择

    8G内存的话,一般开个AS,再启动默认的模拟器的话,基本就有点卡了,如果再打开Idea,很容易卡死. 所以两个spingboot的后台服务只能直接命令行跑个jar包,不方便调试,webview加载的v ...

  10. 并不对劲的bzoj4001:loj2105:p3978:[TJOI2015]概率论

    题目大意 随机生成一棵\(n\)(n\leq10^9)个节点的有根二叉树,问叶子结点个数的期望. 题解 subtask 1:\(n\leq100\),70pts 结论:不同的\(n\)个节点的有根二叉 ...