實體 轉爲 xml 工具類
調用
String reqXml = XmlUtils.toStrGF(實體, true, false);
package product.util;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import cn.hutool.core.util.XmlUtil;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class XmlUtils extends XmlUtil {
@SuppressWarnings("unchecked")
public static <T> T parseBean(String xml, Class<T> clazz) {
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
public static String toStr(Object obj) {
return toStr(obj, false, true);
}
public static String toStr(Object obj, boolean isFormat, boolean isIgnoreHead) {
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormat);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, isIgnoreHead);
marshaller.setProperty(CharacterEscapeHandler.class.getName(),
new CharacterEscapeHandler() {
@Override
public void escape(char[] ch, int start, int length,
boolean isAttVal, Writer writer) throws IOException {
writer.write(ch, start, length);
}
});
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
public static String toPrettyStr(Object obj) {
return toStr(obj, true, true);
}
public static String toStrGF(Object obj, boolean isFormat, boolean isIgnoreHead) {
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, isFormat);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, isIgnoreHead);
marshaller.setProperty(CharacterEscapeHandler.class.getName(),
new CharacterEscapeHandler() {
@Override
public void escape(char[] ch, int start, int length,
boolean isAttVal, Writer writer) throws IOException {
writer.write(ch, start, length);
}
});
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
}
糊塗工具類 cn.hutool.core.util
package cn.hutool.core.util;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
public class XmlUtil {
public final static String INVALID_REGEX = "[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]";
public final static int INDENT_DEFAULT = 2;
public static Document readXML(File file) {
Assert.notNull(file, "Xml file is null !");
if (false == file.exists()) {
throw new UtilException("File [{}] not a exist!", file.getAbsolutePath());
}
if (false == file.isFile()) {
throw new UtilException("[{}] not a file!", file.getAbsolutePath());
}
try {
file = file.getCanonicalFile();
} catch (IOException e) {
}
BufferedInputStream in = null;
try {
in = FileUtil.getInputStream(file);
return readXML(in);
} finally {
IoUtil.close(in);
}
}
public static Document readXML(String pathOrContent) {
if (StrUtil.startWith(pathOrContent, '<')) {
return parseXml(pathOrContent);
}
return readXML(FileUtil.file(pathOrContent));
}
public static Document readXML(InputStream inputStream) throws UtilException {
return readXML(new InputSource(inputStream));
}
public static Document readXML(Reader reader) throws UtilException {
return readXML(new InputSource(reader));
}
public static Document readXML(InputSource source) {
final DocumentBuilder builder = createDocumentBuilder();
try {
return builder.parse(source);
} catch (Exception e) {
throw new UtilException(e, "Parse XML from stream error!");
}
}
public static Document parseXml(String xmlStr) {
if (StrUtil.isBlank(xmlStr)) {
throw new IllegalArgumentException("XML content string is empty !");
}
xmlStr = cleanInvalid(xmlStr);
return readXML(new InputSource(StrUtil.getReader(xmlStr)));
}
public static <T> T readObjectFromXml(File source) throws IOException {
return readObjectFromXml(new InputSource(FileUtil.getInputStream(source)));
}
public static <T> T readObjectFromXml(String xmlStr) throws IOException {
return readObjectFromXml(new InputSource(StrUtil.getReader(xmlStr)));
}
@SuppressWarnings("unchecked")
public static <T> T readObjectFromXml(InputSource source) throws IOException {
Object result = null;
XMLDecoder xmldec = null;
try {
xmldec = new XMLDecoder(source);
result = xmldec.readObject();
} finally {
IoUtil.close(xmldec);
}
return (T) result;
}
public static String toStr(Document doc) {
return toStr(doc, false);
}
public static String toStr(Document doc, boolean isPretty) {
return toStr(doc, CharsetUtil.UTF_8, isPretty);
}
public static String toStr(Document doc, String charset, boolean isPretty) {
final StringWriter writer = StrUtil.getWriter();
try {
write(doc, writer, charset, isPretty ? INDENT_DEFAULT : 0);
} catch (Exception e) {
throw new UtilException(e, "Trans xml document to string error!");
}
return writer.toString();
}
public static String format(Document doc) {
return toStr(doc, true);
}
public static String format(String xmlStr) {
return format(parseXml(xmlStr));
}
public static void toFile(Document doc, String absolutePath) {
toFile(doc, absolutePath, null);
}
public static void toFile(Document doc, String path, String charset) {
if (StrUtil.isBlank(charset)) {
charset = doc.getXmlEncoding();
}
if (StrUtil.isBlank(charset)) {
charset = CharsetUtil.UTF_8;
}
BufferedWriter writer = null;
try {
writer = FileUtil.getWriter(path, charset, false);
write(doc, writer, charset, INDENT_DEFAULT);
} finally {
IoUtil.close(writer);
}
}
public static void write(Node node, Writer writer, String charset, int indent) {
transform(new DOMSource(node), new StreamResult(writer), charset, indent);
}
public static void write(Node node, OutputStream out, String charset, int indent) {
transform(new DOMSource(node), new StreamResult(out), charset, indent);
}
public static void transform(Source source, Result result, String charset, int indent) {
final TransformerFactory factory = TransformerFactory.newInstance();
try {
final Transformer xformer = factory.newTransformer();
if (indent > 0) {
xformer.setOutputProperty(OutputKeys.INDENT, "yes");
xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
}
if (StrUtil.isNotBlank(charset)) {
xformer.setOutputProperty(OutputKeys.ENCODING, charset);
}
xformer.transform(source, result);
} catch (Exception e) {
throw new UtilException(e, "Trans xml document to string error!");
}
}
public static Document createXml() {
return createDocumentBuilder().newDocument();
}
public static DocumentBuilder createDocumentBuilder() {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
disableXXE(dbf);
DocumentBuilder builder = null;
try {
builder = dbf.newDocumentBuilder();
} catch (Exception e) {
throw new UtilException(e, "Create xml document error!");
}
return builder;
}
public static Document createXml(String rootElementName) {
final Document doc = createXml();
doc.appendChild(doc.createElement(rootElementName));
return doc;
}
public static Element getRootElement(Document doc) {
return (null == doc) ? null : doc.getDocumentElement();
}
public static String cleanInvalid(String xmlContent) {
if (xmlContent == null) {
return null;
}
return xmlContent.replaceAll(INVALID_REGEX, "");
}
public static List<Element> getElements(Element element, String tagName) {
final NodeList nodeList = StrUtil.isBlank(tagName) ? element.getChildNodes() : element.getElementsByTagName(tagName);
return transElements(element, nodeList);
}
public static Element getElement(Element element, String tagName) {
final NodeList nodeList = element.getElementsByTagName(tagName);
if (nodeList == null || nodeList.getLength() < 1) {
return null;
}
int length = nodeList.getLength();
for (int i = 0; i < length; i++) {
Element childEle = (Element) nodeList.item(i);
if (childEle == null || childEle.getParentNode() == element) {
return childEle;
}
}
return null;
}
public static String elementText(Element element, String tagName) {
Element child = getElement(element, tagName);
return child == null ? null : child.getTextContent();
}
public static String elementText(Element element, String tagName, String defaultValue) {
Element child = getElement(element, tagName);
return child == null ? defaultValue : child.getTextContent();
}
public static List<Element> transElements(NodeList nodeList) {
return transElements(null, nodeList);
}
public static List<Element> transElements(Element parentEle, NodeList nodeList) {
int length = nodeList.getLength();
final ArrayList<Element> elements = new ArrayList<Element>(length);
Node node;
Element element;
for (int i = 0; i < length; i++) {
node = nodeList.item(i);
if (Node.ELEMENT_NODE == node.getNodeType()) {
element = (Element) nodeList.item(i);
if (parentEle == null || element.getParentNode() == parentEle) {
elements.add(element);
}
}
}
return elements;
}
public static void writeObjectAsXml(File dest, Object bean) throws IOException {
XMLEncoder xmlenc = null;
try {
xmlenc = new XMLEncoder(FileUtil.getOutputStream(dest));
xmlenc.writeObject(bean);
} finally {
IoUtil.close(xmlenc);
}
}
public static XPath createXPath() {
return XPathFactory.newInstance().newXPath();
}
public static Element getElementByXPath(String expression, Object source) {
return (Element) getNodeByXPath(expression, source);
}
public static NodeList getNodeListByXPath(String expression, Object source) {
return (NodeList) getByXPath(expression, source, XPathConstants.NODESET);
}
public static Node getNodeByXPath(String expression, Object source) {
return (Node) getByXPath(expression, source, XPathConstants.NODE);
}
public static Object getByXPath(String expression, Object source, QName returnType) {
final XPath xPath = createXPath();
try {
if (source instanceof InputSource) {
return xPath.evaluate(expression, (InputSource) source, returnType);
} else {
return xPath.evaluate(expression, source, returnType);
}
} catch (XPathExpressionException e) {
throw new UtilException(e);
}
}
public static String escape(String string) {
final StringBuilder sb = new StringBuilder(string.length());
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
public static Map<String, Object> xmlToMap(String xmlStr) {
return xmlToMap(xmlStr, new HashMap<String, Object>());
}
public static Map<String, Object> xmlToMap(Node node) {
return xmlToMap(node, new HashMap<String, Object>());
}
public static Map<String, Object> xmlToMap(String xmlStr, Map<String, Object> result) {
final Document doc = parseXml(xmlStr);
final Element root = getRootElement(doc);
root.normalize();
return xmlToMap(root, result);
}
public static Map<String, Object> xmlToMap(Node node, Map<String, Object> result) {
if (null == result) {
result = new HashMap<>();
}
final NodeList nodeList = node.getChildNodes();
final int length = nodeList.getLength();
Node childNode;
Element childEle;
for (int i = 0; i < length; ++i) {
childNode = nodeList.item(i);
if (isElement(childNode)) {
childEle = (Element) childNode;
result.put(childEle.getNodeName(), childEle.getTextContent());
}
}
return result;
}
public static String mapToXmlStr(Map<?, ?> data, String rootName) {
return toStr(mapToXml(data, rootName));
}
public static Document mapToXml(Map<?, ?> data, String rootName) {
final Document doc = createXml();
final Element root = appendChild(doc, rootName);
mapToXml(doc, root, data);
return doc;
}
public static boolean isElement(Node node) {
return (null == node) ? false : Node.ELEMENT_NODE == node.getNodeType();
}
public static Element appendChild(Node node, String tagName) {
Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument();
Element child = doc.createElement(tagName);
node.appendChild(child);
return child;
}
private static void mapToXml(Document doc, Element element, Map<?, ?> data) {
Element filedEle;
Object key;
for (Entry<?, ?> entry : data.entrySet()) {
key = entry.getKey();
if (null != key) {
filedEle = doc.createElement(key.toString());
element.appendChild(filedEle);
final Object value = entry.getValue();
if (null != value) {
if (value instanceof Map) {
mapToXml(doc, filedEle, (Map<?, ?>) value);
element.appendChild(filedEle);
} else {
filedEle.appendChild(doc.createTextNode(value.toString()));
}
}
}
}
}
private static DocumentBuilderFactory disableXXE(DocumentBuilderFactory dbf) {
String feature;
try {
feature = "http://apache.org/xml/features/disallow-doctype-decl";
dbf.setFeature(feature, true);
feature = "http://xml.org/sax/features/external-general-entities";
dbf.setFeature(feature, false);
feature = "http://xml.org/sax/features/external-parameter-entities";
dbf.setFeature(feature, false);
feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
dbf.setFeature(feature, false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
} catch (ParserConfigurationException e) {
}
return dbf;
}
}