java中使用原生DOM(org.w3c.dom.*)對xml的操作


 

/*
* 文件名: XmlUtils.java
* 版權信息:CopyRight By liliang ? 2009
* 功能描述:xml操作工具類,提供一些對XML文件常見操作的公有方法。
* 修改人:liliang
* 修改時間:2009-06-26
* 修改內容:獲取指定節點的屬性增加了通過判斷是Element后直接使用getAttirubte(name)的方式獲取。
*/
package com.nnyh.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;
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.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
* XML文件操作相關的工具類。該類的主要功能有:
*
*

1.根據xml文件的名字獲取Document對象。

*

2.根據字節輸入流獲取一個Document對象。

*

3.根據字符串獲取一個Document對象。

*

4.通過XPath表達式獲取單個節點。

*

5.通過XPath表達式獲取多個節點。

*

6.通過XPath表達式獲取字符串值。

*

7.通過XPath表達式獲取布爾值。

*

8.將Document輸出到指定的文件。

*

9.獲取Node節點的屬性值。

*

10.替換node節點。

*

11.將Node節點轉換成字符串。

*

*

*

*
* @author liliang
* @version xmlUtils 1.1
* @since xmlUtils 1.0
*
*/
public class XmlUtils {

/**
* 獲取Document對象。根據xml文件的名字獲取Document對象。
*
* @param file
* 要獲取對象的xml文件全路徑。
* @return 返回獲取到的Document對象。
* @throws IOException
* 如果發生任何 IO 錯誤時拋出此異常。
* @throws SAXException
* 如果發生任何解析錯誤時拋出此異常。
* @throws ParserConfigurationException
* 如果無法創建滿足所請求配置的 DocumentBuilder,將拋出該異常。
* @exception NullPointerException
* 如果file為空時,拋出此異常。
*/
public static Document parseForDoc(final String file) throws SAXException, IOException, SecurityException,
NullPointerException, ParserConfigurationException {
return XmlUtils.parseForDoc(new FileInputStream(file));
}

/**
* 將一個xml字符串解析成Document對象。
*
* @param xmlStr
* 要被解析的xml字符串。
* @param encoding
* 字符串的編碼。
* @return 返回解析后的Document對象。
* @throws IOException
* 如果發生任何 IO 錯誤時拋出此異常。
* @throws SAXException
* 如果發生任何解析錯誤時拋出此異常。
* @throws ParserConfigurationException
* 如果無法創建滿足所請求配置的 DocumentBuilder,將拋出該異常。
*/
public static Document parseForDoc(String xmlStr, String encoding) throws SAXException, IOException,
ParserConfigurationException {
if (xmlStr == null) {
xmlStr = "";
}
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(xmlStr.getBytes(encoding));
return XmlUtils.parseForDoc(byteInputStream);
}

/**
* 獲取Document對象。根據字節輸入流獲取一個Document對象。
*
* @param is
* 獲取對象的字節輸入流。
* @return 返回獲取到的Document對象。如果出現異常,返回null。
* @throws IOException
* 如果發生任何 IO 錯誤時拋出此異常。
* @throws SAXException
* 如果發生任何解析錯誤時拋出此異常。
* @throws ParserConfigurationException
* 如果無法創建滿足所請求配置的 DocumentBuilder,將拋出該異常。
* @exception IllegalArgumentException
* 當 is 為 null 時拋出此異常。
*/
public static Document parseForDoc(final InputStream is) throws SAXException, IOException, ParserConfigurationException,
IllegalArgumentException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(is);
} finally {
is.close();
}
}

/**
* 通過xpath表達式解析某個xml節點。
*
* @param obj
* 要被解析的xml節點對象。
* @param xPath
* xpath表達式。
* @param qName
* 被解析的目標類型。
* @return 返回解析后的對象。
* @throws XPathExpressionException
* 如果不能計算 expression。
*
* @exception RuntimeException
* 創建默認對象模型的 XPathFactory 遇到故障時。
* @exception NullPointerException
* 如果xPath為空時拋出時異常。
*/
private static Object parseByXpath(final Object obj, final String xPath, QName qName) throws NullPointerException,
RuntimeException, XPathExpressionException {
XPathFactory xpathFactory = XPathFactory.newInstance();

XPath path = xpathFactory.newXPath();
return path.evaluate(xPath, obj, qName);
}

/**
* 通過XPath表達式獲取單個節點。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表達式。
* @return 返回獲取到的節點。
*
* @throws XPathExpressionException
* 如果不能計算 expression。
*
* @exception RuntimeException
* 創建默認對象模型的 XPathFactory 遇到故障時。
* @exception NullPointerException
* 如果xPath為空時拋出時異常。
*/
public static Node parseForNode(final Object obj, final String xPath) throws NullPointerException, RuntimeException,
XPathExpressionException

{
return (Node) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODE);
}

/**
* 通過XPath表達式獲取某個xml節點的字符串值。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表達式。
* @return 返回獲取到的節點的字符串值。
*
* @throws XPathExpressionException
* 如果不能計算 expression。
*
* @exception RuntimeException
* 創建默認對象模型的 XPathFactory 遇到故障時。
* @exception NullPointerException
* 如果xPath為空時拋出時異常。
*/
public static String parseForString(final Object obj, final String xPath) throws NullPointerException, RuntimeException,
XPathExpressionException

{

return (String) XmlUtils.parseByXpath(obj, xPath, XPathConstants.STRING);
}

/**
* 通過XPath表達式獲取某個xml節點的布爾值。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表達式。
* @return 返回獲取到的節點的布爾值。
*
* @throws XPathExpressionException
* 如果不能計算 expression。
*
* @exception RuntimeException
* 創建默認對象模型的 XPathFactory 遇到故障時。
* @exception NullPointerException
* 如果xPath為空時拋出時異常。
*/
public static Boolean parseForBoolean(final Object obj, final String xPath) throws NullPointerException, RuntimeException,
XPathExpressionException

{
return (Boolean) XmlUtils.parseByXpath(obj, xPath, XPathConstants.BOOLEAN);
}

/**
* 通過XPath表達式獲取Node列表。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表達式。
* @return 返回獲取到的Node列表。
*
* @throws XPathExpressionException
* 如果不能計算 expression。
*
* @exception RuntimeException
* 創建默認對象模型的 XPathFactory 遇到故障時。
* @exception NullPointerException
* 如果xPath為空時拋出時異常。
*/
public static List parseForNodeList(final Object obj, final String xPath) throws NullPointerException,
RuntimeException, XPathExpressionException

{
List lists = new ArrayList();
NodeList nList = (NodeList) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODESET);
if (nList != null) {
for (int i = 0; i < nList.getLength(); i++) {
lists.add(nList.item(i));
}
}
return lists;
}

/**
* 獲取節點的制定屬性。
*
* @param node
* 節點。
* @param attrName
* 屬性名。
* @return 返回獲取到的屬性值。如果找不到相關的
*
*/
public static String getAttribute(final Object node, final String attrName) {
String result = "";
if ((node != null) && (node instanceof Node)) {
if (((Node) node).getNodeType() == Node.ELEMENT_NODE) {
result = ((Element) node).getAttribute(attrName);
} else {
// 遍歷整個xml某節點指定的屬性
NamedNodeMap attrs = ((Node) node).getAttributes();
if ((attrs.getLength() > 0) && (attrs != null)) {
Node attr = attrs.getNamedItem(attrName);
result = attr.getNodeValue();
}
}
}
return result;
}

/**
* 使用新節點替換原來的舊節點。
*
* @param oldNode
* 要被替換的舊節點。
* @param newNode
*
* 替換后的新節點。
* @exception DOMException
* 如果此節點為不允許
* newNode節點類型的子節點的類型;或者如果要放入的節點為此節點的一個祖先或此節點本身;或者如果此節點為
* Document 類型且替換操作的結果將第二個 DocumentType 或 Element 添加到
* Document 上。 WRONG_DOCUMENT_ERR: 如果 newChild
* 是從不同的文檔創建的,不是從創建此節點的文檔創建的,則引發此異常。
* NO_MODIFICATION_ALLOWED_ERR: 如果此節點或新節點的父節點為只讀的,則引發此異常。
* NOT_FOUND_ERR: 如果 oldChild 不是此節點的子節點,則引發此異常。
* NOT_SUPPORTED_ERR: 如果此節點為 Document 類型,則如果 DOM 實現不支持替換
* DocumentType 子節點或 Element 子節點,則可能引發此異常。
*/
public static void replaceNode(Node oldNode, Node newNode) {
if ((oldNode != null) && (newNode != null)) {
oldNode.getParentNode().replaceChild(newNode, oldNode);
}
}

/**
* 將Document輸出到指定的文件中。
*
* @param fileName
* 文件名。
* @param node
* 要保存的對象。
* @param encoding
* 保存的編碼。
* @throws FileNotFoundException
* 指定的文件名不存在時,拋出此異常。
* @throws TransformerException
* 如果轉換過程中發生不可恢復的錯誤時,拋出此異常。
*/
public static void saveXml(final String fileName, final Node node, String encoding) throws FileNotFoundException,
TransformerException {
XmlUtils.writeXml(new FileOutputStream(fileName), node, encoding);
}

/**
* 將Document輸出成字符串的形式。
*
* @param node
* Node對象。
* @param encoding
* 字符串的編碼。
* @return 返回輸出成的字符串。
* @throws TransformerException
* 如果轉換過程中發生不可恢復的錯誤時,拋出此異常。
* @throws UnsupportedEncodingException
* 指定的字符串編碼不支持時,拋出此異常。
*/
public static String nodeToString(Node node, String encoding) throws TransformerException, UnsupportedEncodingException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XmlUtils.writeXml(outputStream, node, encoding);
return outputStream.toString(encoding);
}

/**
* 將指定的Node寫到指定的OutputStream流中。
*
* @param encoding
* 編碼。
* @param os
* OutputStream流。
* @param node
* Node節點。
* @throws TransformerException
* 如果轉換過程中發生不可恢復的錯誤時,拋出此異常。
*/
private static void writeXml(OutputStream os, Node node, String encoding) throws TransformerException {
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);

DOMSource source = new DOMSource();
source.setNode(node);
StreamResult result = new StreamResult();
result.setOutputStream(os);

transformer.transform(source, result);
}
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM