123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- package com.kmall.admin.cuspay.util;
- import org.dom4j.Attribute;
- import org.dom4j.Document;
- import org.dom4j.Element;
- import org.xml.sax.Attributes;
- import org.xml.sax.InputSource;
- import org.xml.sax.SAXException;
- import org.xml.sax.XMLReader;
- import org.xml.sax.helpers.XMLFilterImpl;
- import javax.xml.bind.JAXBContext;
- import javax.xml.bind.Marshaller;
- import javax.xml.bind.Unmarshaller;
- import javax.xml.parsers.SAXParserFactory;
- import javax.xml.transform.Source;
- import javax.xml.transform.sax.SAXSource;
- import java.io.File;
- import java.io.StringReader;
- import java.io.StringWriter;
- import java.util.*;
- /**
- * XML处理类
- *
- * @author Scott Chen
- * @date 2016/11/15
- */
- public class XmlUtils {
- public static String toXML(Object obj, boolean format) throws Exception {
- try {
- JAXBContext context = JAXBContext.newInstance(obj.getClass());
- Marshaller marshaller = context.createMarshaller();
- //编码格式
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- // 是否格式化生成的xml串
- if (format) {
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- }else{
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
- }
- // 是否省略xm头声明信息
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
- StringWriter writer = new StringWriter();
- marshaller.marshal(obj, writer);
- return writer.toString();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- public static String toXMLInFile(Object obj, String filePath, boolean format) throws Exception {
- try {
- JAXBContext context = JAXBContext.newInstance(obj.getClass());
- Marshaller marshaller = context.createMarshaller();
- //编码格式
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- // 是否格式化生成的xml串
- if (format) {
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
- }else{
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
- }
- // 是否省略xm头声明信息
- marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
- File file = new File(filePath);
- marshaller.marshal(obj, file);
- StringWriter writer = new StringWriter();
- marshaller.marshal(obj, writer);
- return writer.toString();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- @SuppressWarnings("unchecked")
- public static <T> T fromXML(String xmlStr, Class<T> valueType, boolean ignoreNs) throws Exception {
- try {
- JAXBContext context = JAXBContext.newInstance(valueType);
- Unmarshaller unmarshaller = context.createUnmarshaller();
- StringReader reader = new StringReader(xmlStr);
- //解析时,是否忽略命名空间
- if (ignoreNs) {
- /**
- * 忽略命名空间
- * 在序列化和反序列化时通过XMLFilterImpl的匿名实现类实现命名空间及xml节点名称的控制
- */
- SAXParserFactory sax = SAXParserFactory.newInstance();
- //false:忽略命名空间
- sax.setNamespaceAware(false);
- XMLReader xmlReader = sax.newSAXParser().getXMLReader();
- XMLFilterImpl nsfFilter = new XMLFilterImpl() {
- private boolean ignoreNamespace = false;
- @Override
- public void startDocument() throws SAXException {
- super.startDocument();
- }
- @Override
- public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
- if (this.ignoreNamespace){
- uri = "";
- }
- super.startElement(uri, localName, qName, atts);
- }
- @Override
- public void endElement(String uri, String localName, String qName) throws SAXException {
- if (this.ignoreNamespace){
- uri = "";
- }
- super.endElement(uri, localName, localName);
- }
- @Override
- public void startPrefixMapping(String prefix, String url) throws SAXException {
- if (!this.ignoreNamespace){
- super.startPrefixMapping("", url);
- }
- }
- };
- nsfFilter.setParent(xmlReader);
- Source source = new SAXSource(xmlReader, new InputSource(reader));
- return (T) unmarshaller.unmarshal(source);
- }
- return (T) unmarshaller.unmarshal(reader);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- public static String map2Xml(Map<String, String> map) {
- StringBuffer sb = new StringBuffer();
- sb.append("<xml>");
- Set es = map.entrySet();
- Iterator it = es.iterator();
- while(it.hasNext()) {
- Map.Entry entry = (Map.Entry)it.next();
- String k = (String)entry.getKey();
- String v = (String)entry.getValue();
- //注意,有一些值要用![CDATA[value]]来表示
- // if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
- // sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
- // continue;
- // }else {
- sb.append("<"+k+">"+v+"</"+k+">");
- // }
- }
- sb.append("</xml>");
- return sb.toString();
- }
- public static Map<String, Object> Dom2Map(Document doc) {
- Map<String, Object> map = new HashMap<>();
- if (doc == null)
- return map;
- Element root = doc.getRootElement();
- for (Iterator<Element> iterator = root.elementIterator(); iterator.hasNext(); ) {
- Element e = iterator.next();
- List list = e.elements();
- if (list.size() > 0) {
- map.put(e.getName(), Dom2Map(e));
- continue;
- }
- map.put(e.getName(), e.getText());
- }
- return map;
- }
- private static Map Dom2Map(Element e) {
- Map<Object, Object> map = new HashMap<>();
- List<Element> list = e.elements();
- if (list.size() > 0) {
- for (int i = 0; i < list.size(); i++) {
- Element iter = list.get(i);
- List<Object> mapList = new ArrayList();
- String iterValue = iter.getName();
- if (iter.attributes().size() != 0) {
- Attribute attribute = iter.attribute(0);
- iterValue = attribute.getValue();
- }
- if (iter.elements().size() > 0) {
- Map m = Dom2Map(iter);
- if (map.get(iterValue) != null) {
- Object obj = map.get(iterValue);
- if (!obj.getClass().getName().equals("java.util.ArrayList")) {
- mapList = new ArrayList();
- mapList.add(obj);
- mapList.add(m);
- }
- if (obj.getClass().getName().equals("java.util.ArrayList")) {
- mapList = (List<Object>)obj;
- mapList.add(m);
- }
- map.put(iterValue, mapList);
- } else {
- map.put(iterValue, m);
- }
- } else if (map.get(iterValue) != null) {
- Object obj = map.get(iterValue);
- if (!obj.getClass().getName().equals("java.util.ArrayList")) {
- mapList = new ArrayList();
- mapList.add(obj);
- mapList.add(iter.getText());
- }
- if (obj.getClass().getName().equals("java.util.ArrayList")) {
- mapList = (List<Object>)obj;
- mapList.add(iter.getText());
- }
- map.put(iterValue, mapList);
- } else {
- map.put(iterValue, iter.getText());
- }
- }
- } else {
- map.put(e.getName(), e.getText());
- }
- return map;
- }
- }
|