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 ...
随机推荐
- 最基本的Unix系统操作命令
基本知识点: OSX 采用的Unix文件系统,所有文件都挂在跟目录 / 下面,所以不在要有Windows 下的盘符概念. 你在桌面上看到的硬盘都挂在 /Volumes 下. 比如接上个叫做 USBHD ...
- C#判断一个类中有无"指定名称"的方法
C#中可以通过反射分析元数据来解决这个问题,示例代码如下: 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 26 2 ...
- Vehicle’s communication protocol
http://www.crecorder.com/techInfo/commuProtocols.jsp COMMUNICATION PROTOCOLS A “communication protoc ...
- 微信公共服务平台开发(.Net 的实现)10-------地理位置
微信公共平台中涉及到地理位置的有两种情况: 第一.我发送一个自选的地理位置给微信,然后微信可以自动反馈响应的信息. 第二.让微信获取我们GPS定位地址位置,反馈响应的信息. 首 ...
- wampserver下打开phpMyAdmin出现403错误的问题解决方法
图1 图2 wamp下打开phpMyAdmin出现403错误的问题解决方法安装完wamp后打开其下的phpMyAdmin也就是路径http://localhost/phpmyadmin/ 出现[图一] ...
- Understanding page frames and pages
Memory in Linux is organized in the form of pages (typically 4 KB in size). Contiguous linear addres ...
- Progressive JPEG
和Baseline一遍扫描不同,Progressive JPEG文件包含多次扫描,这些扫描顺寻的存储在JPEG文件中.打开文件过程中,会先显示整个图片的模糊轮廓,随着扫描次数的增加,图片变得越来越清晰 ...
- 排序命令sort
Unix和Linux自带的sort命令功能非常强大,其主要功能是对文本内容按不同的方法排序.它不仅可以按一个或多个字段排序,还可以合并文件.使用sort处理一些较大的文件时,可能处理速度会比较慢,但却 ...
- offer档次排名,2014最新版
转自:http://tieba.baidu.com/p/2748469183 综合考虑发展,薪水,环境,压力. 第0档:美国互联网总部special offer(15万刀起薪) 第一档: 股份制银行总 ...
- SSMTP—让Linux系统从Office 365发送邮件
SSMTP-让Linux系统从Office 365发送邮件 导读 SSMTP 是一个非常简单实用的小工具,它可以将 Linux 系统的电子邮件中继到 Office 365.Google 或其它第三方 ...