Java操作XML的工具类
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer; import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource; import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.ProcessingInstruction;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; public class XMLUtil {
/**
* 以编码为UTF-8的方式返回xml
* @param doc Document
* @return String
*/
public static String toString(Document doc) {
return toString(doc, "UTF-8");
} /**
* 以指定编码格式返回xml
* @param doc Document
* @param encoding String
* @return String
*/
public static String toString(Document doc, String encoding) {
if (null != doc) {
OutputFormat outputFormat = new OutputFormat();
outputFormat.setEncoding(encoding);
StringWriter stringWriter = new StringWriter();
XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
try {
xmlWriter.write(doc);
return stringWriter.toString();
} catch (IOException ex) {
return "";
}
} else {
return "";
}
} private static String converPath( String path ){
if(OSUtil.LIUNX.equals(System.getProperty("os.name"))){
path = OSUtil.convert2linuxPath(path) ;
System.out.println( "system is Linux , path conver to :" + path );
}
return path ;
} /**
* 创建xml格式的文件
* @param doc
* @param encoding
* @param strFileName
* @return
*/
public static boolean saveXMLDocumentToFile(Document doc, String encoding, String strFileName) {
boolean flag = false;
// 创建路径
strFileName = converPath(strFileName);
String strDir = FileNameUtil.extractFilePath(strFileName);
DirectoryUtil.forceDirectory(strDir); if (encoding == null || encoding.length() == 0) {
encoding = "UTF-8";
}
OutputFormat outputFormat = new OutputFormat();
outputFormat.setEncoding(encoding);
FileOutputStream fos = null;
XMLWriter xmlWriter = null;
try {
// FileWriter fileWriter = new FileWriter(strFileName);
// XMLWriter xmlWriter = new XMLWriter(fileWriter, outputFormat);//
// 不能解决UTF-8编码问题
fos = new FileOutputStream(strFileName);// 可解决UTF-8编码问题
xmlWriter = new XMLWriter(fos, outputFormat);
xmlWriter.write(doc);
flag = true;
} catch (IOException e) {
flag = false;
System.out.println("保存xml文件出错:" + e.getMessage());
e.printStackTrace();
} finally {
try {
if (xmlWriter != null) {
xmlWriter.flush();
}
if (fos != null) {
fos.flush();
}
if (xmlWriter != null) {
xmlWriter.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
} /**
* 创建格式化过的xml格式的文件
* @param doc
* @param encoding
* @param strFileName
* @return
*/
public static boolean saveFormatXMLDocumentToFile(Document doc, String encoding,
String strFileName) {
boolean flag = false; // 创建路径
strFileName = converPath(strFileName);
String strDir = FileNameUtil.extractFilePath(strFileName) ;
DirectoryUtil.forceDirectory(strDir); if (encoding == null || encoding.length() == 0) {
encoding = "UTF-8";
}
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding(encoding);
FileOutputStream fos = null;
XMLWriter xmlWriter = null;
try{
fos = new FileOutputStream(strFileName);// 可解决UTF-8编码问题
xmlWriter = new XMLWriter(fos, outputFormat);
xmlWriter.write(doc);
flag = true;
}catch(IOException e){
flag = false;
}finally{
try {
xmlWriter.flush();
fos.flush();
xmlWriter.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
} }
return flag;
} public static void saveXMLDocumentToOutputStream(Document doc,
String encoding, OutputStream outputstream) throws IOException {
if (encoding == null || encoding.length() == 0) {
encoding = "UTF-8";
}
OutputFormat outputFormat = new OutputFormat();
outputFormat.setEncoding(encoding);
XMLWriter xmlWriter = new XMLWriter(outputstream, outputFormat);
xmlWriter.write(doc);
xmlWriter.close();
outputstream.close();
} public static Document loadXMLFile(String strFileName)
throws DocumentException {
SAXReader saxReader = new SAXReader();
saxReader.setValidation(false);
saxReader.setEntityResolver(new IgnoreDTDEntityResolver());
return saxReader.read(new File(OSUtil.convert2linuxPath(strFileName)));
} public static Document loadXMLInputstream(InputStream in){
SAXReader reader = new SAXReader();
try {
return reader.read(in);
} catch (DocumentException e) {
return null;
}
} /**
* 用于xml 与 xsl 的归并输出含处理指令的xml到out
* 处理指令指定了浏览器渲染的时候使用的xsl文件相对路径
*
* @author sun
*/
@SuppressWarnings("unchecked")
public static void outputXML(Document xmldoc, String xslname,
Writer out) throws Exception {
if (xslname != null) {
ProcessingInstruction pi = DocumentHelper
.createProcessingInstruction("xml-stylesheet", "href=\""
+ xslname + "\" type=\"text/xsl\"");
xmldoc.content().add(0, pi);
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8"); transformer
.transform(new DocumentSource(xmldoc), new StreamResult(out));
out.flush();
out.close();
} /**
* 用于xml 与 xsl 的归并输出xml或html到out
* 输出html时,xsl名称不能为null
* @author
* @throws TransformerException
*/
public static void transformXml(Document xmldoc, String xslname,
Writer out) throws TransformerException{
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = xslname == null ? factory.newTransformer()
: factory.newTransformer(new StreamSource(xslname));
transformer.setOutputProperty("encoding", "UTF-8"); transformer.transform(new DocumentSource(xmldoc),
new StreamResult(out));
}
}
Java操作XML的工具类的更多相关文章
- 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!
转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...
- Java操作字符串的工具类
操作字符串的工具类 import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStre ...
- Java操作图片的工具类
操作图片的工具类: import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.a ...
- Java 操作jar包工具类以及如何快速修改Jar包里的文件内容
需求背景:写了一个实时读取日志文件以及监控的小程序,打包成了Jar包可执行文件,通过我们的web主系统上传到各个服务器,然后调用ssh命令执行.每次上传前都要通过解压缩软件修改或者替换里面的配置文件, ...
- Java操作XML的工具:JAXB
JavaArchitecture for XML Binding (JAXB) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术.该过程中,JAXB也提供了将XML实例文档反向 ...
- java操作数组的工具类-Arrays
static int binarySearch(type[] a, type key) 使用二分搜索法来搜索key元素在数组中的索引:若a数组不包括key,返回负数.(该方法必须已按升序排列后调用). ...
- Java操作XML的JAXB工具
在java中操作XML的工作中中,比较方便的工具是JAXB(Java Architecture for XML Binding). 利用这个工具很方便生成XML的tag和Java类的对应关系.参照网上 ...
- java里poi操作excel的工具类(兼容各版本)
转: java里poi操作excel的工具类(兼容各版本) 下面是文件内具体内容,文件下载: import java.io.FileNotFoundException; import java.io. ...
- Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类
FileService.java也就是操作sdcard的工具类: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ...
随机推荐
- jquery下拉框实现将左边的选项添加到右边区域
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- cocos2d-x 判断两条直线是否相交
bool GraphicsUtil::linesCross(b2Vec2 v0, b2Vec2 v1, b2Vec2 t0, b2Vec2 t1, b2Vec2 &intersectionPo ...
- C++学习笔记之迭代器
模板是的算法独立于存储的数据类型,而迭代器使算法独立于使用的容器类型.理解迭代器是理解STL的关键. 迭代器应该具备的特征: (1)应该能够对迭代器进行解除引用的操作,以便能够访问它引用的值.即如果P ...
- HDU 5597 GTW likes function 打表
GTW likes function 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5596 Description Now you are give ...
- C#中简单调用MD5方法以及MD5简介
MD5简介: MD5的全称是Message-Digest Algorithm 5,在90年代初由MIT的计算机科学实验室和RSA Data Security Inc发明,经MD2.M ...
- 搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)
整合Spring和Mybatis 首先给出完整的项目目录: (1)引入项目需要的jar包 使用http://maven.apache.org作为中央仓库即可. Spring核心包,mybatis核心包 ...
- JSP中Session的使用
JSP session使用方法 <%@page contentType="text/html;charset=GB2312"%><html> <he ...
- 安卓开发之使用viewpager+fragment实现滚动tab页
闲着.用viewpager+fragment实现了个滚动tab..轻拍,以后会陆续发先小东西出来..爱分享,才快乐.demo见附件.. package com.example.demo; import ...
- 【Backbone】简介
1.Model 2.Collection 3.View 4.Router 5.History 6.Events http://addyosmani.github.io/backbone-fundame ...
- Redis缓存服务搭建及实现数据读写
发现博客园中好多大牛在介绍自己的开源项目是很少用到缓存,比如Memcached.Redis.mongodb等,今天得空抽时间把Redis缓存研究了一下,写下来总结一下,跟大家一起分享 一下.由于小弟水 ...