package com.linzl.cn.xml;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.DocumentSource;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;
/**
* 读写性能最佳 依赖dom4j.jar jaxen-1.1-beta-4.jar 对于复杂格式的xml更合适
*
* @author linzl 最后修改时间:2014年10月10日
*/
public class Dom4jUtils {
/**
* 使用JDK自带的类转换Document对象转成字符串
*
* @param doc
* @return
* @throws TransformerException
*/
public static String docToString(Document doc) throws TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty("encoding", doc.getXMLEncoding());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// 此处代码 和JDK本身的dom稍有不同
transformer.transform(new DocumentSource(doc), new StreamResult(bos));
return bos.toString();
}
/**
* xml文件转Document 有时该方法未必能用, 建议使用stringToDoc将文件读成string后再转
*
* @param file
* @return
* @throws DocumentException
* @throws FileNotFoundException
*/
public static Document fileToDoc(File file) throws DocumentException,
FileNotFoundException {
SAXReader reader = new SAXReader();
Document doc = reader.read(file);
doc.normalize();
return doc;
}
/**
* xml文件转Document 有时该方法未必能用, 建议使用stringToDoc将文件读成string后再转
*
* @param is
* @return
* @throws DocumentException
*/
public static Document fileToDoc(InputStream is) throws DocumentException {
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
doc.normalize();
return doc;
}
/**
* 字符串内容转换成Document对象
*
* @param xmlStr
* @return
* @throws DocumentException
*/
public static Document stringToDoc(String xmlContent) throws DocumentException {
Document doc = DocumentHelper.parseText(xmlContent);
return doc;
}
/**
* 将xmlStr格式化输出到目标文件
*
* @param doc
* @param targetFile
* @throws IOException
*/
public static void formatToXMLFile(Document doc, File targetFile)
throws IOException {
OutputFormat outformat = OutputFormat.createPrettyPrint();
// xml自身的编码
outformat.setEncoding(doc.getXMLEncoding());
outformat.setIndent(true);
// 将xmlStr输出到目标路径,使用xml文件的头文件编码
OutputStream out = new FileOutputStream(targetFile);
XMLWriter writer = new XMLWriter(out, outformat);
writer.write(doc);
writer.flush();
}
/**
* 将xmlContent格式化输出到目标文件
*
* @param xmlContent
* @param targetFile
* @throws TransformerException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws DocumentException
*/
public static void formatToXMLFile(String xmlContent, File targetFile)
throws TransformerException, ParserConfigurationException,
SAXException, IOException, DocumentException {
Document doc = stringToDoc(xmlContent);
formatToXMLFile(doc, targetFile);
}
/**
* 将xml文件格式化输出到目标文件
*
* @param srcFile
* xml源文件
* @param targetFile
* 格式化输出xml文件
* @throws TransformerException
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws DocumentException
*/
public static void formatToXMLFile(File srcFile, File targetFile)
throws TransformerException, ParserConfigurationException,
SAXException, IOException, DocumentException {
Document doc = fileToDoc(srcFile);
formatToXMLFile(doc, targetFile);
}
/**
* 打印Document的结点基本信息
*
* @param doc
*/
public static void printNode(Document doc) {
Element root = doc.getRootElement();
printRecursive(root);
}
/**
* 递归打印结点信息
*
* @param element
*/
private static void printRecursive(Element element) {
// 首先获取当前节点的所有属性节点
Iterator<Attribute> iter = element.attributeIterator();
// 遍历属性节点
Attribute attribute = null;
while (iter.hasNext()) {
attribute = (Attribute) iter.next();
System.out.println("结点" + element.getName() + "--》属性"
+ attribute.getName() + ":" + attribute.getValue());
}
iter = element.elementIterator();
Element temp = null;
while (iter.hasNext()) {
temp = (Element) iter.next();
System.out.println("------------------------");
System.out.println(temp.getName());
System.out.println("值--》" + temp.getTextTrim());
printRecursive(temp);
}
}
/**
* Dom4j 的Dom的生成: 直接按照从上到下的结点顺序addElement
*
* @return
* @throws IOException
*/
public static void createDocXML() throws IOException {
Document doc = DocumentHelper.createDocument();
doc.addComment("根结点注释");
Element root = doc.addElement("root");
Element rootChildA = root.addElement("rootChildA");
rootChildA.setText("rootChildA孩子结点");
rootChildA.addAttribute("name", "姓名");
rootChildA.addAttribute("age", "年龄");
rootChildA.addAttribute("height", "身高");
Element rootChildB = root.addElement("rootChildB");
// CDATA 指的是不应由 XML 解析器进行解析的文本数据
rootChildB.setText("<![CDATA[rootChildB孩子结点]]>");
File file = new File("D:/dom4j.xml");
OutputStream os = new FileOutputStream(file);
OutputFormat outformat = OutputFormat.createPrettyPrint();
// xml自身的编码
outformat.setEncoding(doc.getXMLEncoding());
outformat.setIndent(true);
XMLWriter writer = new XMLWriter(os, outformat);
// 是否转义字符,默认true转义,false表示不转义
writer.setEscapeText(false);
writer.write(doc);
writer.flush();
}
/**
* Document对象格式化成字符串
*
* @param doc
* @return
* @throws IOException
*/
public static String formatDocToString(Document doc) throws IOException {
OutputFormat outformat = OutputFormat.createPrettyPrint();
// xml自身的编码
outformat.setEncoding(doc.getXMLEncoding());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
XMLWriter writer = new XMLWriter(bos, outformat);
writer.write(doc);
writer.flush();
return bos.toString();
}
/**
* Document对象转成xml字符串
*
* @param doc
* @return
*/
public static String docAsXML(Document doc) {
return doc.asXML();
}
public static void removeNode() {
}
public static void updateNode() {
}
public static void main(String[] args) throws Exception {
// InputStream is = Dom4jUtils.class
// .getResourceAsStream(“/com/linzl/cn/xml/xmlRead.xml”);
//
// is = Dom4jUtils.class.getClassLoader().getResourceAsStream(
// “com/linzl/cn/xml/xmlRead.xml”);
// Document doc = fileToDoc(is);
// printNode(doc);
//
// createDocXML();
String file =”F:\anjianOAdoc\oadoc\taitan\missive\3189-apacheBase64.xml”;
String target =”F:\anjianOAdoc\oadoc\taitan\missive\757-副本.xml”;
String xmlStr = FileUtils.readFileToString(new File(file));
formatToXMLFile(xmlStr, new File(target));
}
}