package com.unisure.xmlUtil;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import com.unisure.util.Map;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class XmlUtil {
private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
/**
* 把Document对象转为字符串
*
* @return
*/
public String outXMLData(Document document) {
return DomToString.getStringFromDocument(document);
}
/**
* 将Map转换成一个Document对象
*
* @param rootName
* @param secondName
* @param map
* @return
* @throws ParserConfigurationException
*/
public String outXMLData(String rootName, String secondName, Map map) throws ParserConfigurationException {
Document doc = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().newDocument();
Element root = doc.createElement(rootName);
Element secondEle = doc.createElement(secondName);
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (key == null) {
continue;
}
if (value == null) {
value = "";
}
String name = String.valueOf(key.toString().toLowerCase());
String text = String.valueOf(value);
// 给 rootEmt 节点添加子节点并赋值
Element temp = doc.createElement(name);
Text textNode = doc.createTextNode(stripNonValidXMLCharacters(text));
temp.appendChild(textNode);
secondEle.appendChild(temp);
}
root.appendChild(secondEle);
doc.appendChild(root);
BASE64Encoder encoder = new BASE64Encoder();
try {
return encoder.encode(outXMLData(doc).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 把字符串转为Document对象
*
* @return
* @throws IOException
* @throws JDOMException
*/
public Document parseXMLDocument(String xmlStr) {
return DomParser.getDocument(xmlStr);
}
/**
* 把字符串转为Document对象
*
* @return
* @throws IOException
* @throws JDOMException
*/
public Document[] parseXMLDocument(String[] xmlStrs) {
Document[] docs = new Document[xmlStrs.length];
for (int i = 0; i < xmlStrs.length; i++) {
docs[i] = parseXMLDocument(xmlStrs[i]);
}
return docs;
}
/**
* 解析返回数据结果集
*
* @param xmlStr
* @return
*/
public List[] parseXMLToListArray(String xmlStr) {
BASE64Decoder decoder = new BASE64Decoder();
try {
xmlStr = new String(decoder.decodeBuffer(xmlStr), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
// PrettyPrinter.println(xmlStr);
Document doc = parseXMLDocument(xmlStr);
Node tempRoot = doc.getFirstChild();
NodeList rows = tempRoot.getChildNodes();
List list = new LinkedList();
List list1 = new LinkedList();
List list2 = new LinkedList();
List list3 = new LinkedList();
for (int i = 0; i < rows.getLength(); i++) {
Node element = (Node) rows.item(i);
NodeList columns = element.getChildNodes();
Map rec = new Map();
for (int j = 0; j < columns.getLength(); j++) {
Node tempElement = (Node) columns.item(j);
String name = tempElement.getNodeName();
String value = "";
if (tempElement.getFirstChild() != null)
value = tempElement.getFirstChild().getNodeValue();
rec.put(name, value);
}
if (element.getNodeName().equals("CollectionInfo")) {
list.add(rec);
} else if (element.getNodeName().equals("BaseInfo")) {
list1.add(rec);
} else if (element.getNodeName().equals("ListContent")) {
list2.add(rec);
} else if (element.getNodeName().equals("SubList")) {
list3.add(rec);
}
}
return new List[] { list, list1, list2, list3 };
}
/**
* 批量数据执行时,将List转换成Document对象
*
* @param baseInfo
* @param list
* @return
* @throws ParserConfigurationException
*/
public String outXMLData(Map baseInfo, List list) throws ParserConfigurationException {
Document doc = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder().newDocument();
Element root = doc.createElement("DataSet");
if (baseInfo != null) {
Element baseInfoEle = doc.createElement("BaseInfo");
Iterator it = baseInfo.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
Element temp = doc.createElement(key);
String text = baseInfo.getString(key);
Text textNode = doc.createTextNode(stripNonValidXMLCharacters(text));
temp.appendChild(textNode);
baseInfoEle.appendChild(temp);
}
root.appendChild(baseInfoEle);
}
for (int i = 0; i < list.size(); i++) {
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
Element listContentEle = doc.createElement("ListContent");
Map map = (Map) list.get(i);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (key == null) {
continue;
}
if (value == null) {
value = "";
}
String name = String.valueOf(key.toString().toLowerCase());
String text = String.valueOf(value);
// 给 rootEmt 节点添加子节点并赋值
Element temp = doc.createElement(name);
Text textNode = doc.createTextNode(text);
temp.appendChild(textNode);
listContentEle.appendChild(temp);
}
root.appendChild(listContentEle);
}
doc.appendChild(root);
BASE64Encoder encoder = new BASE64Encoder();
try {
return encoder.encode(this.outXMLData(doc).getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 过滤特殊字符
*
* @param in
* @return
*/
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer();
char current;
if (in == null || ("".equals(in))) {
return "";
}
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i);
if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF))) {
out.append(current);
}
}
return out.toString();
}
}
用到的其他方法
package com.unisure.utils;
import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class DomToString {
public static String getStringFromDocument(Document doc) {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
transformer.transform(domSource, result);
} catch (Exception e) {
throw new IllegalStateException();
}
return writer.toString();
}
}
DomParser.java
package com.unisure.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.IOUtils;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class DomParser {
public static Document getDocument(File xmlFile) {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
return docBuilder.parse(xmlFile);
} catch (ParserConfigurationException e) {
throw new IllegalStateException();
} catch (SAXException e) {
throw new IllegalStateException();
} catch (IOException e) {
throw new IllegalStateException();
}
}
public static Document getDocument(String xmlString) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlString));
return builder.parse(is);
} catch (ParserConfigurationException e) {
throw new IllegalStateException();
} catch (SAXException e) {
throw new IllegalStateException();
} catch (IOException e) {
throw new IllegalStateException();
}
}
public static Document parse(InputStream in) {
Document document = null;
if (in == null)
return null;
DOMParser parser = new DOMParser();
try {
parser.parse(new InputSource(in));
} catch (SAXException e) {
throw new IllegalStateException();
} catch (IOException e) {
throw new IllegalStateException();
}
document = parser.getDocument();
return document;
}
public static Document parseXmlWithRelativeFilePath(String relativeXmlPath) {
InputStream stream = DomParser.class.getClassLoader().getResourceAsStream(relativeXmlPath);
try {
return parse(stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
public static Document parseXmlWithAbsFilePath(String absoluteFilePath) {
InputStream stream = null;
try {
stream = new FileInputStream(absoluteFilePath);
return parse(stream);
} catch (FileNotFoundException fnfEx) {
throw new IllegalArgumentException();
} finally {
if (stream != null) {
IOUtils.closeQuietly(stream);
}
}
}
public static Document parseXmlString(String xmlString) {
InputStream stream = new ByteArrayInputStream(xmlString.getBytes());
try {
return parse(stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
}
DomEditor.java
package com.unisure.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.xerces.dom.DocumentImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public final class DomEditor {
private DomEditor() {
super();
}
public static void addAttributeToElement(Document doc, Element projectElement, String attributeName, String attributeValue) {
Attr xmlnsAttr = doc.createAttribute(attributeName);
xmlnsAttr.setValue(attributeValue);
projectElement.setAttributeNode(xmlnsAttr);
}
/**
* 更新一个标签的值
*
* @param doc
* @param tagName
* @param tagValue
*/
public static void replaceTagValue(Document doc, String tagName, String tagValue) {
NodeList nodeList = doc.getElementsByTagName(tagName);
int j = nodeList.getLength();
Node node;
for (int i = 0; i < j; i++) {
Node newNode = doc.createTextNode(tagValue);
node = nodeList.item(i);
if (node.getFirstChild() != null) {
node.replaceChild(newNode, node.getFirstChild());
} else {
node.appendChild(newNode);
}
}
}
/**
* 在指定的标签后插入一个新的标签
*
* @param d
* @param appendTo
* @param tagName
* @param tagValue
* @return
*/
public static Element insertNewTagBelow(Document d, String appendTo, String tagName, String tagValue) {
Node element = d.getElementsByTagName(appendTo).item(0);
if (element == null) {
element = d.createElement(appendTo);
}
Element newElement = d.createElement(tagName);
element.appendChild(newElement);
newElement.appendChild(d.createTextNode(tagValue));
return newElement;
}
/**
* 在指定的标签下插入一个新值
*
* @param doc
* @param tagName
* @param tagValue
* @return
*/
public static Element insertTagValue(Document doc, String tagName, String tagValue) {
Element element = doc.createElement(tagName);
doc.getDocumentElement().appendChild(element);
if (tagValue != null) {
element.appendChild(doc.createTextNode(tagValue));
}
return element;
}
/**
* 在指定的标签下插入一个新值
*
* @param document
* @param elementToAppend
* @param tagName
* @param tagValue
* @return
*/
public static Element insertTagInElement(Document document, Element elementToAppend, String tagName, String tagValue) {
Element newElement = document.createElement(tagName);
elementToAppend.appendChild(newElement);
newElement.appendChild(document.createTextNode(tagValue));
return newElement;
}
/**
* 插入或者更新一个值
*
* @param doc
* @param tagName
* @param tagValue
*/
public static void insertOrUpdateTagValue(Document doc, String tagName, String tagValue) {
if (DomEditor.checkTagExists(doc, tagName)) {
DomEditor.replaceTagValue(doc, tagName, tagValue);
} else {
DomEditor.insertTagValue(doc, tagName, tagValue);
}
}
/**
* 根据指定的对象返回第一个兄弟元素的值,如果没有则返回空
*
* @param element
* @param tagName
* @return
*/
public static String getTagValue(Element element, String tagName) {
if (element == null) {
return null;
}
NodeList nodes = element.getElementsByTagName(tagName);
if (nodes == null || nodes.getLength() <= 0) {
return null;
}
return getTagValueOfFirstChild(nodes.item(0));
}
/**
* 根据指定的对象返回所有兄弟元素的值,如果没有则返回空集合
*
* @param element
* @param tagName
* @return
*/
public static List getTagValues(Element element, String tagName) {
List tagValues = new ArrayList();
List elements = getElements(tagName, element);
for (int i = 0; i < elements.size(); i++) {
Element resultElement = (Element) elements.get(i);
tagValues.add(getTagValue(resultElement, tagName));
}
return tagValues;
}
/**
* 根据指定的对象返回所有兄弟元素的值,如果没有则返回空集合
*
* @param document
* @param tagName
* @return
*/
public static List getTagValues(Document document, String tagName) {
Element element = document.getDocumentElement();
return getTagValues(element, tagName);
}
/**
* 将指定的Element对象转换为Document对象
*
* @param element
* @return
*/
public static Document getDocument(Element element) {
Document doc = new DocumentImpl();
Node node = ((DocumentImpl) doc).importNode(element, true);
doc.appendChild(node);
return doc;
}
/**
* 根据指定的值和对象搜索内容
*
* @param key
* @param doc
* @return
*/
public static String getNodeValue(String key, Document doc) {
return getNodeValue(key, doc.getDocumentElement());
}
/**
* 根据指定的值和对象搜索内容
*
* @param key
* @param contentElement
* @return
*/
public static String getNodeValue(String key, Element contentElement) {
String value = "";
StringTokenizer tokenizer = new StringTokenizer(key, ".", false);
NodeList nodes = null;
while (tokenizer.hasMoreTokens()) {
String tagName = tokenizer.nextToken();
nodes = contentElement.getElementsByTagName(tagName);
contentElement = locateElement(nodes);
if (contentElement == null) {
return null;
}
}
value = getTagValue(contentElement);
return value;
}
/**
* 根据节点名称查询子节点信息
*
* @param node
* @return
*/
public static String getTagValue(Node node) {
NodeList childNodeList = node.getChildNodes();
String value = null;
if (childNodeList == null)
value = "";
else {
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < childNodeList.getLength(); j++) {
buffer.append(childNodeList.item(j).getNodeValue());
}
value = buffer.toString();
}
return value;
}
private static Element locateElement(NodeList nodes) {
if (nodes == null)
return null;
int len = nodes.getLength();
if (len == 0)
return null;
Element elt = null;
for (int i = 0; i < len; i++) {
Node n = nodes.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
elt = (Element) n;
} else {
continue;
}
}
return elt;
}
/**
* 根据节点名称查询子节点信息
*
* @param node
* @return
*/
public static String getTagValueOfFirstChild(Node node) {
NodeList childNodeList = node.getChildNodes();
String value;
if (childNodeList == null) {
value = "";
} else {
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < childNodeList.getLength(); j++) {
buffer.append(childNodeList.item(j).getNodeValue());
}
value = buffer.toString();
}
return value;
}
/**
* 通过标签名称删除标签
*
* @param doc
* @param tagName
*/
public static void deleteTag(Document doc, String tagName) {
NodeList nodeList = doc.getElementsByTagName(tagName);
int j = nodeList.getLength();
Node node;
Node parentNode;
for (int i = 0; i < j; i++) {
node = nodeList.item(i);
parentNode = node.getParentNode();
parentNode.removeChild(node);
}
}
/**
* 查询所有的Element对象
*
* @param tagName
* @param input
* @return
*/
public static List getElements(String tagName, Element input) {
NodeList nodes = input.getElementsByTagName(tagName);
int len = nodes.getLength();
List elt = new ArrayList(len);
Node node;
for (int i = 0; i < len; i++) {
node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
elt.add((Element) node);
}
}
return elt;
}
/**
* 判断在Document中是否存在一个相同的节点
*
* @param doc
* @param tagname
* @return
*/
public static boolean checkTagExists(Document doc, String tagname) {
boolean retVal = true;
NodeList nodes = doc.getElementsByTagName(tagname);
if ((nodes == null) || (nodes.getLength() == 0)) {
retVal = false;
}
return retVal;
}
/**
* 在指定的文档下插入CDAT内容
*
* @param doc
* @param tagName
* @param tagValue
*/
public static void insertCDATASection(Document doc, String tagName, String tagValue) {
NodeList nodeList = doc.getElementsByTagName(tagName);
if (nodeList == null) {
return;
}
int j = nodeList.getLength();
Node node = null;
for (int i = 0; i < j; i++) {
node = nodeList.item(i);
node.appendChild(doc.createCDATASection(tagValue));
}
}
}