轉自:https://blog.csdn.net/wmyasw/article/details/8686420html
package com.mymhotel.opera;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class DOMUtils {
/**
* 初始化一個空Document對象返回。
*
* @return a Document
*/
public static Document newXMLDocument() {
try {
return newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 初始化一個DocumentBuilder
*
* @return a DocumentBuilder
* @throws ParserConfigurationException
*/
public static DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException {
return newDocumentBuilderFactory().newDocumentBuilder();
}
/**
* 初始化一個DocumentBuilderFactory
*
* @return a DocumentBuilderFactory
*/
public static DocumentBuilderFactory newDocumentBuilderFactory() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
return dbf;
}
/**
* 將傳入的一個XML String轉換成一個org.w3c.dom.Document對象返回。
*
* @param xmlString
* 一個符合XML規範的字符串表達。
* @return a Document
*/
public static Document parseXMLDocument(String xmlString) {
if (xmlString == null) {
throw new IllegalArgumentException();
}
try {
return newDocumentBuilder().parse(
new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 給定一個輸入流,解析爲一個org.w3c.dom.Document對象返回。
*
* @param input
* @return a org.w3c.dom.Document
*/
public static Document parseXMLDocument(InputStream input) {
if (input == null) {
throw new IllegalArgumentException("參數爲null!");
}
try {
return newDocumentBuilder().parse(input);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 給定一個文件名,獲取該文件並解析爲一個org.w3c.dom.Document對象返回。
*
* @param fileName
* 待解析文件的文件名
* @return a org.w3c.dom.Document
*/
public static Document loadXMLDocumentFromFile(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("未指定文件名及其物理路徑!");
}
try {
return newDocumentBuilder().parse(new File(fileName));
} catch (SAXException e) {
throw new IllegalArgumentException("目標文件(" + fileName
+ ")不能被正確解析爲XML!" + e.getMessage());
} catch (IOException e) {
throw new IllegalArgumentException("不能獲取目標文件(" + fileName + ")!"
+ e.getMessage());
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}
/*
* 把dom文件轉換爲xml字符串
*/
public static String toStringFromDoc(Document document) {
String result = null;
if (document != null) {
StringWriter strWtr = new StringWriter();
StreamResult strResult = new StreamResult(strWtr);
TransformerFactory tfac = TransformerFactory.newInstance();
try {
javax.xml.transform.Transformer t = tfac.newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,
// text
t.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
t.transform(new DOMSource(document.getDocumentElement()),
strResult);
} catch (Exception e) {
System.err.println("XML.toString(Document): " + e);
}
result = strResult.getWriter().toString();
try {
strWtr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 給定一個節點,將該節點加入新構造的Document中。
*
* @param node
* a Document node
* @return a new Document
*/
public static Document newXMLDocument(Node node) {
Document doc = newXMLDocument();
doc.appendChild(doc.importNode(node, true));
return doc;
}
/**
* 將傳入的一個DOM Node對象輸出成字符串。若是失敗則返回一個空字符串""。
*
* @param node
* DOM Node 對象。
* @return a XML String from node
*/
/*
* public static String toString(Node node) { if (node == null) { throw new
* IllegalArgumentException(); } Transformer transformer = new
* Transformer(); if (transformer != null) { try { StringWriter sw = new
* StringWriter(); transformer .transform(new DOMSource(node), new
* StreamResult(sw)); return sw.toString(); } catch (TransformerException
* te) { throw new RuntimeException(te.getMessage()); } } return ""; }
*/
/**
* 將傳入的一個DOM Node對象輸出成字符串。若是失敗則返回一個空字符串""。
*
* @param node
* DOM Node 對象。
* @return a XML String from node
*/
/*
* public static String toString(Node node) { if (node == null) { throw new
* IllegalArgumentException(); } Transformer transformer = new
* Transformer(); if (transformer != null) { try { StringWriter sw = new
* StringWriter(); transformer .transform(new DOMSource(node), new
* StreamResult(sw)); return sw.toString(); } catch (TransformerException
* te) { throw new RuntimeException(te.getMessage()); } } return ""; }
*/
/**
* 獲取一個Transformer對象,因爲使用時都作相同的初始化,因此提取出來做爲公共方法。
*
* @return a Transformer encoding gb2312
*/
public static Transformer newTransformer() {
try {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
Properties properties = transformer.getOutputProperties();
properties.setProperty(OutputKeys.ENCODING, "gb2312");
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.VERSION, "1.0");
properties.setProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperties(properties);
return transformer;
} catch (TransformerConfigurationException tce) {
throw new RuntimeException(tce.getMessage());
}
}
/**
* 返回一段XML表述的錯誤信息。提示信息的TITLE爲:系統錯誤。之因此使用字符串拼裝,主要是這樣作通常 不會有異常出現。
*
* @param errMsg
* 提示錯誤信息
* @return a XML String show err msg
*/
/*
* public static String errXMLString(String errMsg) { StringBuffer msg = new
* StringBuffer(100);
* msg.append("<?xml version="1.0" encoding="gb2312" ?>");
* msg.append("<errNode title="系統錯誤" errMsg="" + errMsg + ""/>"); return
* msg.toString(); }
*/
/**
* 返回一段XML表述的錯誤信息。提示信息的TITLE爲:系統錯誤
*
* @param errMsg
* 提示錯誤信息
* @param errClass
* 拋出該錯誤的類,用於提取錯誤來源信息。
* @return a XML String show err msg
*/
/*
* public static String errXMLString(String errMsg, Class errClass) {
* StringBuffer msg = new StringBuffer(100);
* msg.append("<?xml version='1.0' encoding='gb2312' ?>");
* msg.append("<errNode title="
* 系統錯誤" errMsg=""+ errMsg + "" errSource=""+ errClass.getName()+ ""/>");
* return msg.toString(); }
*/
/**
* 返回一段XML表述的錯誤信息。
*
* @param title
* 提示的title
* @param errMsg
* 提示錯誤信息
* @param errClass
* 拋出該錯誤的類,用於提取錯誤來源信息。
* @return a XML String show err msg
*/
public static String errXMLString(String title, String errMsg,
Class errClass) {
StringBuffer msg = new StringBuffer(100);
msg.append("<?xml version='1.0' encoding='utf-8' ?>");
msg.append("<errNode title=" + title + "errMsg=" + errMsg
+ "errSource=" + errClass.getName() + "/>");
return msg.toString();
}
}
java
————————————————
版權聲明:本文爲CSDN博主「wmyasw」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。
原文連接:https://blog.csdn.net/wmyasw/article/details/8686420node