whyclxw
2025-02-13 d62fa80f3d12a56ae60eeef45f07cea6477c2507
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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();
    }
}