一、前言
关于if-util-3.2.8.jar包中对XML进行类解析XMLDOMParser、加密XMLEncoder、常用操作XMLOperator(获取子节点元素、节点名称及元素数组等待)、XML序列化XMLSerializer、XML格式转换XMLTransformer、工具类操作XMLUtil(获取指定key值getProperty、xml转换文本对象str2Xml等)、XML校验XMLValidator等。
二、源码说明
1、XMLDOMParser
package com.bill99.seashell.common.util.xml;@b@@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import javax.xml.parsers.DocumentBuilder;@b@import javax.xml.parsers.DocumentBuilderFactory;@b@import javax.xml.parsers.ParserConfigurationException;@b@import org.w3c.dom.Document;@b@import org.xml.sax.InputSource;@b@import org.xml.sax.SAXException;@b@@b@public class XMLDOMParser@b@{@b@ public static Document parse(InputSource input)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();@b@ DocumentBuilder builder = factory.newDocumentBuilder();@b@ return builder.parse(input);@b@ }@b@@b@ public static Document parse(InputStream inputStream)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ InputSource inputSource = new InputSource(inputStream);@b@ return parse(inputSource);@b@ }@b@@b@ public static Document parse(File file)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ InputStream inputStream = new FileInputStream(file);@b@ return parse(inputStream);@b@ }@b@}
2、XMLEncoder
package com.bill99.seashell.common.util.xml;@b@@b@public class XMLEncoder@b@{@b@ public static String encode(String source)@b@ {@b@ if (source == null) return null;@b@ String result = null;@b@ StringBuffer sb = new StringBuffer();@b@@b@ for (int i = 0; i < source.length(); ++i) {@b@ char c = source.charAt(i);@b@ switch (c)@b@ {@b@ case '&':@b@ sb.append("&");@b@ break;@b@ case '<':@b@ sb.append("<");@b@ break;@b@ case '"':@b@ sb.append(""");@b@ break;@b@ case '\'':@b@ sb.append("'");@b@ break;@b@ case '>':@b@ sb.append(">");@b@ break;@b@ default:@b@ sb.append(c);@b@ }@b@ }@b@ result = sb.toString();@b@ return result;@b@ }@b@}
3、XMLOperator
package com.bill99.seashell.common.util.xml;@b@@b@import java.io.File;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.util.HashMap;@b@import java.util.LinkedList;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.TreeMap;@b@import javax.xml.parsers.DocumentBuilder;@b@import javax.xml.parsers.DocumentBuilderFactory;@b@import javax.xml.parsers.ParserConfigurationException;@b@import org.springframework.util.Assert;@b@import org.w3c.dom.Document;@b@import org.w3c.dom.Element;@b@import org.w3c.dom.Node;@b@import org.w3c.dom.NodeList;@b@import org.w3c.dom.Text;@b@import org.xml.sax.InputSource;@b@import org.xml.sax.SAXException;@b@@b@public final class XMLOperator@b@{@b@ public static Element appendNewElement(Element e, String elementName)@b@ {@b@ if ((elementName == null) || ("".equals(elementName.trim())))@b@ throw new IllegalArgumentException("element name cannot be null");@b@@b@ Element element = e;@b@ Element newElement = null;@b@ Document doc = null;@b@@b@ if (element == null) {@b@ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();@b@@b@ DocumentBuilder builder = null;@b@ try {@b@ builder = factory.newDocumentBuilder();@b@ } catch (ParserConfigurationException ex) {@b@ throw new IllegalStateException("Failed to get a document builder");@b@ }@b@@b@ doc = builder.newDocument();@b@ newElement = doc.createElement(elementName);@b@ element = (Element)doc.appendChild(newElement);@b@ return element;@b@ }@b@@b@ doc = element.getOwnerDocument();@b@ newElement = doc.createElement(elementName);@b@ element = (Element)element.appendChild(newElement);@b@ return element;@b@ }@b@@b@ public static void setElementText(Element element, String value)@b@ {@b@ if (element == null) {@b@ throw new IllegalArgumentException("cannot set text to null element");@b@ }@b@@b@ String elementValue = value;@b@ Document doc = null;@b@ Text text = null;@b@@b@ if (elementValue == null) {@b@ elementValue = "";@b@ }@b@@b@ doc = element.getOwnerDocument();@b@ text = doc.createTextNode(elementValue);@b@ element.appendChild(text);@b@ }@b@@b@ public static void setElementText(Element element, long value)@b@ {@b@ setElementText(element, Long.toString(value));@b@ }@b@@b@ public static void setElementText(Element element, boolean value)@b@ {@b@ setElementText(element, Boolean.toString(value));@b@ }@b@@b@ public static String getChildText(Element parent, String name)@b@ {@b@ Element e = getChildByName(parent, name);@b@ if (e == null)@b@ return "";@b@@b@ return getText(e);@b@ }@b@@b@ public static String getText(Element e)@b@ {@b@ NodeList nl = e.getChildNodes();@b@ int max = nl.getLength();@b@ for (int i = 0; i < max; ++i) {@b@ Node n = nl.item(i);@b@ if (n.getNodeType() == 3)@b@ return n.getNodeValue();@b@ }@b@@b@ return "";@b@ }@b@@b@ public static Element getChildByName(Element e, String name)@b@ {@b@ Element[] list = getChildrenByName(e, name);@b@ if (list.length == 0)@b@ return null;@b@@b@ if (list.length > 1)@b@ throw new IllegalStateException("Too many elements found!");@b@@b@ return list[0];@b@ }@b@@b@ public static Element[] getChildrenByName(Element e, String name)@b@ {@b@ NodeList nl = e.getChildNodes();@b@ int max = nl.getLength();@b@ LinkedList list = new LinkedList();@b@ for (int i = 0; i < max; ++i) {@b@ Node n = nl.item(i);@b@ if ((n.getNodeType() == 1) && (n.getNodeName().equals(name)))@b@ {@b@ list.add(n);@b@ }@b@ }@b@ return ((Element[])(Element[])list.toArray(new Element[list.size()]));@b@ }@b@@b@ public Object getAllDataFromXml(File file)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ Assert.notNull(file, "File must be not null");@b@ Document doc = XMLDOMParser.parse(file);@b@ Node root = doc.getDocumentElement();@b@ GetNode getnode = new GetNode(this, root);@b@ return GetNode.access$000(getnode);@b@ }@b@@b@ public Object getAllDataFromXml(InputSource inputSource)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ Assert.notNull(inputSource, "InputSource must be not null");@b@ Document doc = XMLDOMParser.parse(inputSource);@b@ Node root = doc.getDocumentElement();@b@ GetNode getnode = new GetNode(this, root);@b@ return GetNode.access$000(getnode);@b@ }@b@@b@ public Object getAllDataFromXml(InputStream input)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ Assert.notNull(input, "InputStream must be not null");@b@ Document doc = XMLDOMParser.parse(input);@b@ Node root = doc.getDocumentElement();@b@ GetNode getnode = new GetNode(this, root);@b@ return GetNode.access$000(getnode);@b@ }@b@@b@ public Object GetAllDataFromXml(Node nodeT, boolean isMulchild)@b@ {@b@ Assert.notNull(nodeT, "nodeT must be not null");@b@ GetNode getnode = new GetNode(this, nodeT, isMulchild);@b@ return GetNode.access$000(getnode);@b@ }@b@@b@ private final class GetNode@b@ {@b@ private final Node root;@b@ private final boolean isMulchild;@b@@b@ public GetNode(, Node paramNode)@b@ {@b@ this(paramXMLOperator, nodeT, true); }@b@@b@ public GetNode(, Node paramNode, boolean paramBoolean) {@b@ this.root = paramNode;@b@ this.isMulchild = paramBoolean;@b@ }@b@@b@ private Object getAllNodeValue()@b@ {@b@ Map result;@b@ Node n;@b@ Assert.notNull(this.root, "root must be not null");@b@ NodeList nodeList = this.root.getChildNodes();@b@ if (!(this.isMulchild)) {@b@ result = new TreeMap();@b@ i = 0; for (len = nodeList.getLength(); i < len; ++i) {@b@ n = nodeList.item(i);@b@ if (n.getNodeType() == 1)@b@ getNodeValue(n, result);@b@ }@b@@b@ return result;@b@ }@b@ if (nodeList.getLength() == 1) {@b@ result = new HashMap();@b@ getNodeValue(nodeList.item(1), result);@b@ return result;@b@ }@b@ List resultList = new LinkedList();@b@ int i = 0; for (int len = nodeList.getLength(); i < len; ++i) {@b@ n = nodeList.item(i);@b@ if (n.getNodeType() == 1) {@b@ Map map = new HashMap();@b@ getNodeValue(n, map);@b@ resultList.add(map);@b@ }@b@ }@b@ if (resultList.size() == 1)@b@ return resultList.get(0);@b@@b@ return resultList;@b@ }@b@@b@ private void getNodeValue(, Map map)@b@ {@b@ int i;@b@ Assert.notNull(node, "node must be not null");@b@ Assert.notNull(map, "map must be not null");@b@ NodeList nl = node.getChildNodes();@b@ if (nl.getLength() == 1) {@b@ Node n = nl.item(0);@b@ if (n.getNodeType() == 3) {@b@ Text t = (Text)n;@b@ String name = n.getParentNode().getNodeName();@b@ String value = t.getNodeValue();@b@ map.put(name, value);@b@ }@b@ }@b@ else {@b@ i = 0; for (int len = nl.getLength(); i < len; ++i) {@b@ Node n = nl.item(i);@b@ getNodeValue(n, map);@b@ }@b@ }@b@ }@b@ }@b@}
4、XMLSerializer
package com.bill99.seashell.common.util.xml;@b@@b@import java.io.IOException;@b@import java.io.OutputStream;@b@import java.io.Writer;@b@import java.util.Properties;@b@import javax.xml.transform.Transformer;@b@import javax.xml.transform.TransformerConfigurationException;@b@import javax.xml.transform.TransformerException;@b@import javax.xml.transform.TransformerFactory;@b@import javax.xml.transform.dom.DOMSource;@b@import javax.xml.transform.stream.StreamResult;@b@import org.w3c.dom.Node;@b@@b@public class XMLSerializer@b@{@b@ public static void serialize(Node doc, Writer out)@b@ throws TransformerConfigurationException, TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer trans = factory.newTransformer();@b@ trans.setOutputProperty("omit-xml-declaration", "yes");@b@ trans.transform(new DOMSource(doc), new StreamResult(out));@b@ out.flush();@b@ }@b@@b@ public static void serialize(Node doc, Writer out, Properties props)@b@ throws TransformerConfigurationException, TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer trans = factory.newTransformer();@b@ if (props != null)@b@ trans.setOutputProperties(props);@b@@b@ trans.transform(new DOMSource(doc), new StreamResult(out));@b@ out.flush();@b@ }@b@@b@ public static void serialize(Node doc, OutputStream out)@b@ throws TransformerConfigurationException, TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer trans = factory.newTransformer();@b@ trans.setOutputProperty("omit-xml-declaration", "yes");@b@ trans.transform(new DOMSource(doc), new StreamResult(out));@b@ out.flush();@b@ }@b@@b@ public static void serialize(Node doc, OutputStream out, Properties props)@b@ throws TransformerConfigurationException, TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer trans = factory.newTransformer();@b@ if (props != null)@b@ trans.setOutputProperties(props);@b@@b@ trans.transform(new DOMSource(doc), new StreamResult(out));@b@ out.flush();@b@ }@b@}
5、XMLTransformer
package com.bill99.seashell.common.util.xml;@b@@b@import java.io.IOException;@b@import java.io.OutputStream;@b@import java.io.Writer;@b@import java.util.Properties;@b@import javax.xml.transform.Source;@b@import javax.xml.transform.Transformer;@b@import javax.xml.transform.TransformerException;@b@import javax.xml.transform.TransformerFactory;@b@import javax.xml.transform.stream.StreamResult;@b@@b@public class XMLTransformer@b@{@b@ public static void transform(Source xml, Source xsl, Writer out)@b@ throws TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer t = factory.newTransformer(xsl);@b@ t.setOutputProperty("omit-xml-declaration", "yes");@b@ t.transform(xml, new StreamResult(out));@b@ out.flush();@b@ }@b@@b@ public static void transform(Source xml, Source xsl, Writer out, Properties props)@b@ throws TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer t = factory.newTransformer(xsl);@b@ if (props != null)@b@ t.setOutputProperties(props);@b@@b@ t.transform(xml, new StreamResult(out));@b@ out.flush();@b@ }@b@@b@ public static void transform(Source xml, Source xsl, OutputStream out)@b@ throws TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer t = factory.newTransformer(xsl);@b@ t.setOutputProperty("omit-xml-declaration", "yes");@b@ t.transform(xml, new StreamResult(out));@b@ out.flush();@b@ }@b@@b@ public static void transform(Source xml, Source xsl, OutputStream out, Properties props)@b@ throws TransformerException, IOException@b@ {@b@ TransformerFactory factory = TransformerFactory.newInstance();@b@ Transformer t = factory.newTransformer(xsl);@b@ if (props != null)@b@ t.setOutputProperties(props);@b@@b@ t.transform(xml, new StreamResult(out));@b@ out.flush();@b@ }@b@}
6、XMLUtil
package com.bill99.seashell.common.util.xml;@b@@b@import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.io.PrintStream;@b@import java.io.StringReader;@b@import java.util.HashMap;@b@import java.util.Map;@b@import java.util.StringTokenizer;@b@import javax.xml.parsers.DocumentBuilder;@b@import javax.xml.parsers.DocumentBuilderFactory;@b@import javax.xml.parsers.ParserConfigurationException;@b@import javax.xml.transform.Transformer;@b@import javax.xml.transform.TransformerException;@b@import javax.xml.transform.TransformerFactory;@b@import javax.xml.transform.dom.DOMSource;@b@import javax.xml.transform.stream.StreamResult;@b@import org.springframework.util.Assert;@b@import org.w3c.dom.Document;@b@import org.w3c.dom.NamedNodeMap;@b@import org.w3c.dom.Node;@b@import org.w3c.dom.NodeList;@b@import org.xml.sax.InputSource;@b@import org.xml.sax.SAXException;@b@@b@public class XMLUtil@b@{@b@ private Node rootNode;@b@ private Document doc;@b@ private String xmlStr;@b@@b@ public XMLUtil(String xmlStr)@b@ {@b@ this.xmlStr = xmlStr;@b@ initWithXmlStr();@b@ }@b@@b@ public Document getDoc()@b@ {@b@ return this.doc; }@b@@b@ public void initWithXmlStr() {@b@ DocumentBuilderFactory factory;@b@ try {@b@ factory = DocumentBuilderFactory.newInstance();@b@@b@ factory.setIgnoringComments(true);@b@ factory.setIgnoringElementContentWhitespace(true);@b@ DocumentBuilder build = factory.newDocumentBuilder();@b@ this.doc = build.parse(new ByteArrayInputStream(this.xmlStr.getBytes("UTF-8")));@b@ this.rootNode = this.doc;@b@ }@b@ catch (Exception e) {@b@ System.out.println(e.getMessage());@b@ }@b@ }@b@@b@ public static String xml2Str(Document doc) throws TransformerException@b@ {@b@ TransformerFactory tf = TransformerFactory.newInstance();@b@ Transformer t = tf.newTransformer();@b@ t.setOutputProperty("encoding", "UTF-8");@b@ ByteArrayOutputStream bos = new ByteArrayOutputStream();@b@ t.transform(new DOMSource(doc), new StreamResult(bos));@b@ String xmlStr = bos.toString();@b@ return xmlStr;@b@ }@b@@b@ public static Document str2Xml(String xmlStr)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ StringReader sr = new StringReader(xmlStr);@b@ InputSource is = new InputSource(sr);@b@ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();@b@ DocumentBuilder builder = factory.newDocumentBuilder();@b@ Document doc = builder.parse(is);@b@ return doc;@b@ }@b@@b@ public String getProperty(String key)@b@ {@b@ int index = key.lastIndexOf(46);@b@ String propertyName = key.substring(index + 1);@b@ Node node = getNode(key, false);@b@ if (node == null)@b@ return "";@b@@b@ NamedNodeMap attrs = node.getAttributes();@b@ Node attr = attrs.getNamedItem(propertyName);@b@ if (attr == null)@b@ return "";@b@@b@ return attr.getNodeValue();@b@ }@b@@b@ public String getValue(String key) {@b@ Node node = getNode(key, true);@b@ if (node == null)@b@ return "";@b@@b@ Node temp = node.getFirstChild();@b@ if (null == temp)@b@ return "";@b@@b@ return temp.getNodeValue();@b@ }@b@@b@ public Node getNode(String key, boolean isGetValue)@b@ {@b@ StringTokenizer st = new StringTokenizer(key, ".");@b@ Node currentNode = this.rootNode;@b@ Node preNode = null;@b@ int count = st.countTokens();@b@ for (int i = 0; i < count; ++i) {@b@ if (null == currentNode)@b@ return null;@b@@b@ if ((!(isGetValue)) && (i == count - 1))@b@ return currentNode;@b@@b@ preNode = currentNode;@b@ String nodeName = (String)st.nextElement();@b@ NodeList nodes = currentNode.getChildNodes();@b@ int len = nodes.getLength();@b@ for (int j = 0; j < len; ++j) {@b@ Node node = nodes.item(j);@b@ if (nodeName.equalsIgnoreCase(node.getNodeName())) {@b@ currentNode = node;@b@ break;@b@ }@b@ }@b@ if (currentNode == preNode)@b@ return null;@b@@b@ }@b@@b@ return currentNode;@b@ }@b@@b@ public void setNodeValue(String key, String value) {@b@ Node node = getNode(key, true);@b@ Assert.notNull(node, "node must be not null");@b@ Assert.notNull(value, "node's value must be not null");@b@ if (node.hasChildNodes())@b@ node.getFirstChild().setNodeValue(value);@b@ else@b@ node.appendChild(this.doc.createTextNode(value));@b@ }@b@@b@ public static String replace(String xml, Map value)@b@ {@b@ int len = xml.length();@b@ StringBuffer buf = new StringBuffer(len);@b@ for (int i = 0; i < len; ++i) {@b@ char c = xml.charAt(i);@b@ if (c == '$') {@b@ ++i;@b@ StringBuffer key = new StringBuffer();@b@ char temp = xml.charAt(i);@b@ while (temp != '}') {@b@ if (temp != '{')@b@ key.append(temp);@b@@b@ ++i;@b@ temp = xml.charAt(i);@b@ }@b@ String variable = (String)value.get(key.toString());@b@ if (null == variable)@b@ buf.append("");@b@ else@b@ buf.append(variable);@b@ }@b@ else {@b@ buf.append(c);@b@ }@b@ }@b@ return buf.toString();@b@ }@b@@b@ public static void main(String[] args) throws Exception {@b@ String test = "<?xml version=\"1.0\" encoding=\"GBK\"?><ICBC><B2C><SubmitOrder><merID>${id}</merID></SubmitOrder></B2C></ICBC>";@b@ Map map = new HashMap();@b@ map.put("id", "1");@b@ String result = replace(test, map);@b@ test = "<?xml version=\"1.0\" encoding=\"GBK\"?><ICBC><B2C><aa/><SubmitOrder><merID>商户代码</merID></SubmitOrder></B2C></ICBC>";@b@ test = "<?xml version = '1.0' encoding = 'UTF-8'?><Preference><Accounting><ClosedAcctPeriodDate/></Accounting> <Login>3<MaxAttempts/> <FailedWindowTime/> </Login> <Register>4<DefaultServiceLevel/> </Register></Preference>";@b@ XMLUtil util = new XMLUtil(test);@b@@b@ Node node = util.getNode("Preference.Accounting.ClosedAcctPeriodDate", true);@b@@b@ Document doc = util.getDoc();@b@ node.appendChild(doc.createTextNode("aa"));@b@ System.out.println(node.getNodeName());@b@ System.out.println(node.getFirstChild().getNodeValue());@b@ }@b@}
7、XMLValidator
package com.bill99.seashell.common.util.xml;@b@@b@import java.io.IOException;@b@import java.io.PrintStream;@b@import javax.xml.parsers.ParserConfigurationException;@b@import javax.xml.parsers.SAXParser;@b@import javax.xml.parsers.SAXParserFactory;@b@import org.xml.sax.ErrorHandler;@b@import org.xml.sax.InputSource;@b@import org.xml.sax.SAXException;@b@import org.xml.sax.SAXParseException;@b@import org.xml.sax.XMLReader;@b@import org.xml.sax.helpers.DefaultHandler;@b@@b@public class XMLValidator extends DefaultHandler@b@{@b@ static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";@b@@b@ public static void validate(InputSource input)@b@ throws ParserConfigurationException, SAXException, IOException@b@ {@b@ SAXParserFactory spf = SAXParserFactory.newInstance();@b@ spf.setNamespaceAware(true);@b@ spf.setValidating(true);@b@@b@ SAXParser saxParser = spf.newSAXParser();@b@@b@ XMLReader xmlReader = saxParser.getXMLReader();@b@@b@ xmlReader.setContentHandler(new XMLValidator());@b@@b@ xmlReader.setErrorHandler(new MyErrorHandler(System.err));@b@@b@ xmlReader.parse(input);@b@ System.out.println("parse success.........");@b@ }@b@@b@ private static class MyErrorHandler implements ErrorHandler@b@ {@b@ private PrintStream out;@b@@b@ MyErrorHandler(PrintStream out)@b@ {@b@ this.out = out;@b@ }@b@@b@ private String getParseExceptionInfo(SAXParseException spe)@b@ {@b@ String systemId = spe.getSystemId();@b@ if (systemId == null)@b@ systemId = "null";@b@@b@ String info = "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage();@b@@b@ return info;@b@ }@b@@b@ public void warning(SAXParseException spe)@b@ throws SAXException@b@ {@b@ this.out.println("Warning: " + getParseExceptionInfo(spe));@b@ }@b@@b@ public void error(SAXParseException spe) throws SAXException {@b@ String message = "Error: " + getParseExceptionInfo(spe);@b@ throw new SAXException(message);@b@ }@b@@b@ public void fatalError(SAXParseException spe) throws SAXException {@b@ String message = "Fatal Error: " + getParseExceptionInfo(spe);@b@ throw new SAXException(message);@b@ }@b@ }@b@}