package com.whyc.webService.util;
|
|
import com.whyc.webService.dto.request.RequestParam;
|
import com.whyc.webService.dto.response.response1.ResponseResult;
|
import com.whyc.webService.dto.response.response2.ResponseResult2;
|
|
import javax.xml.bind.JAXBContext;
|
import javax.xml.bind.JAXBException;
|
import javax.xml.bind.Marshaller;
|
import javax.xml.bind.Unmarshaller;
|
import java.io.StringReader;
|
import java.io.StringWriter;
|
|
public class XmlParser {
|
public static RequestParam parseXmlRequest(String info) throws JAXBException {
|
JAXBContext jaxbContext = JAXBContext.newInstance(RequestParam.class);
|
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
|
|
StringReader reader = new StringReader(info);
|
RequestParam param = (RequestParam) unmarshaller.unmarshal(reader);
|
|
return param;
|
}
|
|
public static String toXml(ResponseResult returnInfo) throws JAXBException {
|
JAXBContext jaxbContext = JAXBContext.newInstance(ResponseResult.class);
|
Marshaller marshaller = jaxbContext.createMarshaller();
|
|
// 设置是否格式化输出
|
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
|
// 设置编码 gb2312
|
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gb2312");
|
|
StringWriter writer = new StringWriter();
|
marshaller.marshal(returnInfo, writer);
|
|
return writer.toString();
|
}
|
|
public static String toXml2(ResponseResult2 returnInfo) throws JAXBException {
|
JAXBContext jaxbContext = JAXBContext.newInstance(ResponseResult2.class);
|
Marshaller marshaller = jaxbContext.createMarshaller();
|
|
// 设置是否格式化输出
|
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
|
// 设置编码 gb2312
|
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gb2312");
|
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
|
//marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"gb2312\"?>");
|
StringWriter writer = new StringWriter();
|
marshaller.marshal(returnInfo, writer);
|
|
return "<?xml version=\"1.0\" encoding=\"gb2312\"?>\n" + writer.toString();
|
}
|
}
|