package com.indigopacific.util;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
public class XMLTools {
public static final String DOCUMENT_HEAD = "<?xml version=/"1.0/" encoding=/"GB2312/"?>";
public static final String LINE_SEPERATOR = System
.getProperty("line.separator");
/**
* 根據文件名創建一個文檔對象
*
* @param filePath
* String
* @return Document
*/
public static Document createDocument(String filePath) {
// 輸入參數校驗
if (filePath == null) {
return null;
}
Document document = null;
try {
// 解析文件,獲取一個document對象
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
document = parser.parse(filePath);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return document;
}
// 創建一個文檔對象
public static Document createDocument(InputStream is) {
// 輸入參數校驗
if (is == null) {
return null;
}
Document document = null;
try {
// 解析文件,獲取一個document對象
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder parser = factory.newDocumentBuilder();
document = parser.parse(is);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return document;
}
/**
* 將document寫入到輸入流中
*
* @param document
* @param out
*/
public static void writeDocument(String document, OutputStream out)
throws java.io.IOException {
out.write(document.getBytes());
out.flush();
}
/**
* <company> <person> <name>alan</name> </person> </company>
* 倘若要讀取name的值,path應該爲company/person/name/
*
* @path:xml中從根節點開始到要操作元素的路徑
* @defaultValue:如果沒有找到指定元素的text值,返回缺省值
*/
public static String readElementTextValue(Document document, String path,
String defaultValue) {
// 輸入參數校驗
if ((path == null) || (path.trim().length() == 0)) {
return defaultValue;
}
// 找到該元素
Element element = findElement(document, path);
// 獲取文本子節點
NodeList children = element.getChildNodes();
if (children == null) {
return defaultValue;
}
// 遍歷找到文本節點
for (int i = 0; i < children.getLength(); i++) {
Node _node = children.item(i);
if (_node.getNodeType() == Node.TEXT_NODE) {
return _node.getNodeValue();
}
}
// 如果沒有文本節點,返回缺省值
return defaultValue;
}
/**
* 從根節點開始查找指定位置的節點。 <company> <person> <name>tiger</name> </person>
* </company> 比如要查找name節點,path應該爲“company/person/name”
*
* @param root:根節點
* @param path:節點從根節點開始的路徑。如
* root/a/b
* @return:如果沒有找到,在該位置創建一個新的Element。
*/
public static Element findElement(Document document, String path) {
// 根據path,一層層查找指定路徑的Element
StringTokenizer token = new StringTokenizer(path, "/");
Element parent = null;
// 根據path一層層的查找,直到找到需要的element,如果沒有,則創建新的
while (token.hasMoreTokens()) {
// 如果parent爲null,將根節點作爲父節點
if (parent == null) {
parent = document.getDocumentElement();
token.nextToken();
continue;
}
// 如果要查找的子節點名稱爲空,不處理
String elementName = token.nextToken();
if (elementName.trim() == "") {
continue;
}
// 查找子節點,如果不存在,則創建一個
Element[] childElements = findChildElement(parent, elementName);
if (childElements.length == 0) {
Element childElement = document.createElement(elementName);
parent.appendChild(childElement);
parent = childElement;
} else {
parent = childElements[0];
}
}// end for
return parent;
}
/**
* 在element的孩子節點中,找到所有符合條件的孩子。 例如: <company> <person> <name>alan</name>
* <age>25</age> </person> <person> <name>alan</name> <age>25</age>
* </person> </company>
* element爲person節點,childName指定爲person。那麼兩個person節點就會被加入結果集合中
*
* @param element
* @param <any>
* @return:如果有,則返回符合條件的子節點集合;否則返回空集合
*/
public static Element[] findChildElement(Element element, String childPath) {
// 輸入參數校驗
if ((element == null) || (childPath == null)) {
return new Element[0];
}
// 保存結果集合
List parents = new ArrayList();
parents.add(element);
// 分析childpath
StringTokenizer stringToken = new StringTokenizer(childPath, "/");
while (stringToken.hasMoreTokens()) {
// 保存找到的父節點的子節點集合
List childs = new ArrayList();
// 獲取當前應該找父節點的哪一個子節點了
String childName = stringToken.nextToken();
// 如果節點爲空,返回
if (childName == null || childName.trim().length() == 0) {
continue;
}
// 對於父節點集合進行遍歷
for (int iParent = 0; iParent < parents.size(); iParent++) {
Element parent = (Element) parents.get(iParent);
// 查找父節點的所有子節點
NodeList childNodes = parent.getChildNodes();
// 如果parent沒有子元素,返回空集合
if ((childNodes == null) || (childNodes.getLength() == 0)) {
continue;
}
// 遍歷所有子節點,找到和elementName匹配的節點
for (int i = 0; i < childNodes.getLength(); i++) {
// 如果子節點不是element,不處理
if (childNodes.item(i).getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element child = (Element) childNodes.item(i);
if (childName.equals(child.getNodeName())) {
childs.add(child);
}
} // 結束對於子節點集合的遍歷
}// 結束對於父節點集合的遍歷
// 找到父節點本層的所有子節點後,當前的所有子節點就是下一次遍歷的父節點
parents = childs;
}// 結束所有層的遍歷
// 將list轉換爲數組
Element[] objectArray = new Element[parents.size()];
for (int i = 0; i < objectArray.length; i++) {
objectArray[i] = (Element) parents.get(i);
}
return objectArray;
}
/**
* 無屬性匹配條件的查找。
*
* @param parent
* 父元素。
* @param childTagName
* 待查找的子元素的標記名。
*/
public static Element findChildElement(Node parent, String childElementName) {
return findChildElement(parent, childElementName, null, null);
}
/**
* 根據子節點的名稱和屬性查找一個子節點。如果有多個匹配返回第一個,如果一個 匹配的都沒有,返回null。
*
* @param parent
* 父元素。
* @param childTagName
* 待查找的子元素的標記名。
* @param childAttributeName
* 待查找的子元素要匹配的屬性名。
* @param childAttributeValue
* 待查找的子元素要匹配的屬性值。
*/
public static Element findChildElement(Node parent,
String childElementName, String childAttributeName,
String childAttributeValue) {
NodeList nl = parent.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) { // 所有子節點
Node childNode = nl.item(i);
if (childNode.getNodeName().equals(childElementName)) { // 名字匹配
if (childNode instanceof Element) { // 如果是Element(只有它纔有屬性)
Element childElement = (Element) childNode;
if (childAttributeName == null
|| childElement.getAttribute(childAttributeName)
.equals(childAttributeValue)) { // 屬性匹配條件
return childElement;
}
}
}
}
return null; // 沒有匹配
}
/**
* @throws Exception
* @函數名稱:${getXmlData}
* @創建日期:${2008-11-13}
* @功能說明:解析xml文件獲取節點的值
* @參數說明:節點名稱
* @返回說明:返回xml某個節點的值
*/
public static String getXmlValue(Document xml, String tagName)
throws Exception {
String xmlData = "";
Element elem = (Element) xml.getDocumentElement();
xmlData = getElementByTagName(elem, tagName);
return xmlData;
}
/**
* @函數名稱:${getXmlDoc}
* @創建日期:${2008-11-13}
* @功能說明:得到要解析的xml文件對象
* @參數說明:xml文件的路徑
* @返回說明:文件對象
*/
public static Document getXmlDoc(BufferedReader characterStream)
throws Exception {
Document xmlDoc = null;
DOMParser domparser = new DOMParser();
InputSource inputsource = new InputSource();
inputsource.setCharacterStream(characterStream);
domparser.parse(inputsource);
xmlDoc = domparser.getDocument();
if (characterStream != null) {
characterStream.close();
}
return xmlDoc;
}
public static Document getXmlDoc(InputStream is) throws Exception {
Document xmlDoc = null;
DOMParser domparser = new DOMParser();
InputSource inputsource = new InputSource();
inputsource.setByteStream(is);
domparser.parse(inputsource);
xmlDoc = domparser.getDocument();
if (is != null) {
is.close();
}
return xmlDoc;
}
/**
* @函數名稱:${getElementByTagName}
* @創建日期:${2008-11-13}
* @功能說明:輔助方法,根據節點和節點名稱得到節點值
* @參數說明:父節點、子節點名稱
* @返回說明:節點值
*/
public static String getElementByTagName(Element parentEle, String tagName)
throws Exception {
String retVal = null;
NodeList theNl = (parentEle).getElementsByTagName(tagName);
if (theNl.getLength() > 0) {
if (theNl.item(0).getFirstChild() != null) {
retVal = theNl.item(0).getFirstChild().getNodeValue();
}
}
return retVal;
}
/**
* @函數名稱:${buffer}
* @創建日期:${2008-11-13}
* @功能說明:輔助方法,緩衝數據流
* @參數說明:輸入流、輸出流
* @返回說明:空
*/
public static void buffer(InputStream in, OutputStream out)
throws IOException {
BufferedInputStream bin = new BufferedInputStream(in);
BufferedOutputStream bout = new BufferedOutputStream(out);
while (true) {
int datum = bin.read();
if (datum == -1)
break;
bout.write(datum);
}
bout.flush();
}
public static void main(String[] args) {
}
public XMLTools() {
}
}