共计 5349 个字符,预计需要花费 14 分钟才能阅读完成。
XmlUtils
package com.daily.xmltest;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class XmlUtils {
private final static Logger log = Logger.getLogger(XmlUtils.class);
private static Map<HashSet<Class<?>>, JAXBContext> jaxbContextMap = new HashMap<HashSet<Class<?>>, JAXBContext>();
private static Map<HashSet<Class<?>>, Unmarshaller> unmarshallerMap = new HashMap<HashSet<Class<?>>, Unmarshaller>();
private static XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
static {
xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, true);
}
private static JAXBContext getJaxbInstance(Class… classesToBeBound) throws JAXBException {
return getJaxbInstance(null, classesToBeBound);
}
private static JAXBContext getJaxbInstance(HashSet classes, Class… classesToBeBound) throws JAXBException {
if (classes == null){
classes = new HashSet<Class<?>>(CollectionUtils.arrayToList(classesToBeBound));
}
JAXBContext jaxbContext = jaxbContextMap.get(classes);
if (jaxbContext == null){
jaxbContext = JAXBContext.newInstance(classesToBeBound);
jaxbContextMap.put(classes, jaxbContext);
}
return jaxbContext;
}
private static Unmarshaller getUnmarshallerInstance(Class… classesToBeBound) throws JAXBException {
HashSet classes = new HashSet<Class<?>>(CollectionUtils.arrayToList(classesToBeBound));
Unmarshaller unmarshaller = unmarshallerMap.get(classes);
if (unmarshaller == null){
JAXBContext jaxbContext = getJaxbInstance(classes, classesToBeBound);
unmarshaller = jaxbContext.createUnmarshaller();
unmarshallerMap.put(classes, unmarshaller);
}
return unmarshaller;
}
/**
* 将 javabean 转换为 XML 字符串
* @param object
* @return
*/
public static String convertToXmlStr(Object object, Class… classesToBeBound) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Writer xmlStr = new StringWriter();
try {
if (classesToBeBound == null || classesToBeBound.length == 0){
classesToBeBound = new Class[]{object.getClass()};
}
JAXBContext context = getJaxbInstance(classesToBeBound);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
marshaller.marshal(object, xmlStr);
stopWatch.stop();
log.info(“Object convert to XML str success, ” + xmlStr + “,cost time:” + stopWatch.getTotalTimeMillis() + “ms”);
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if(xmlStr != null) {
try {
xmlStr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return xmlStr.toString().replace(“standalone=\”yes\””, “”);
}
/**
* 将 XML 字符串转换为指定类型的 javabean
* @param classesToBeBound 指定所有 class
* @param xmlStr xml 字符串
* @return
*/
public static Object xmlStrToObject(String xmlStr, Class… classesToBeBound) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object xmlObject = null;
Reader reader = null;
XMLStreamReader xmlStreamReader = null;
try {
log.info(“XML Str convert to Object, xmlStr=” + xmlStr);
JAXBContext context = getJaxbInstance(classesToBeBound);
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xmlStr);
xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);
xmlObject = unmarshaller.unmarshal(xmlStreamReader);
stopWatch.stop();
log.info(“XML Str convert to Object success, ” + JSON.toJSONString(xmlObject) + “,cost time:” + stopWatch.getTotalTimeMillis() + “ms”);
} catch (JAXBException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} finally {
if (null != xmlStreamReader){
try {
xmlStreamReader.close();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return xmlObject;
}
/**
* 获取节点值
* @param xmlStr
* @param nodeName
* @return
*/
public static String getNodeValue(String xmlStr, String nodeName){
if (xmlStr == null) {
return null;
}
int startPos = xmlStr.indexOf(“<” + nodeName + “>”);
if (startPos == -1) {
return null;
}
int endPos = xmlStr.lastIndexOf(“</” + nodeName + “>”);
if (endPos == -1) {
return null;
}
return xmlStr.substring(startPos + (“</” + nodeName + “>”).length() – 1, endPos);
}
}
Bean
package com.daily.xmltest.Bean;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name=”data”)
public class School implements Serializable {
private String schoolName;
private String address;
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
测试
package com.daily.xmltest;
import com.alibaba.fastjson.JSON;
import com.daily.xmltest.Bean.School;
import org.junit.Test;
public class XMLTest {
@Test
public void test() {
School school = new School();
school.setSchoolName(“ 一中 ”);
school.setAddress(“ 益阳 ”);
String schoolStr = XmlUtils.convertToXmlStr(school);
System.out.println(schoolStr);
School parseSchool = (School) XmlUtils.xmlStrToObject(schoolStr, School.class);
System.out.println(JSON.toJSONString(parseSchool));
}
}