xml字符串与java对象相互转换

文章目录

  • 案例类User.java
  • 工具类XmlUtil.java

案例类User.java

import javax.xml.bind.*;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;

@XmlRootElement(name="xml")
//@XmlRootElement关键字必须要有
@XmlAccessorType(XmlAccessType.FIELD)
public class Test implements Serializable {

    private static final long serialVersionUID = 4532246911561026611L;
    
    private String userId;

    private String userName;


    public String getUserId() {
        return userId;
    }


    public void setUserId(String userId) {
        this.userId = userId;
    }


    public String getUserName() {
        return userName;
    }


    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "Test{" +
                "userId='" + userId + '\'' +
                ", userName='" + userName + '\'' +
                '}';
    }

    /**
     * xml字符串转java对象
     * @param xmlString xml字符串
     * @param clazz 要转的java对象
     * @param  泛型
     *
     * @return T
     */
    public static <T> T xmlToBean(String xmlString, Class<T> clazz) throws Exception{
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
        XMLEventReader someSource = factory.createXMLEventReader(stream);

        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        JAXBElement<T> userElement = jaxbUnmarshaller.unmarshal(someSource, clazz);
        return userElement.getValue();
    }

    /**
     * bean对象转xml字符串
     * @param obj bean对象
     * @param clazz 要转的bean.Class
     *
     * @return object
     */
    public static String beanToXml(Object obj, Class<?> clazz) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        return writer.toString();
    }

    /**
     * xml字符串转Object对象
     * @param xmlString xml字符串
     * @param load 要转的bean.Class
     *
     * @return object
     */
    public static Object xmlToObject(String xmlString, Class<?> load) throws JAXBException, IOException {
        JAXBContext context = JAXBContext.newInstance(load);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object object = unmarshaller.unmarshal(new StringReader(xmlString));
        return object;
    }

    public static void main(String[] args) throws Exception {
        String s = "gh_36f64e81bfb8username";
        Object o = xmlToBean(s, Test.class);
        Test u = (Test) o;
        Test test = xmlToBean(s, Test.class);
        System.out.println(test);

        System.out.println(beanToXml(u, Test.class));
    }
}

工具类XmlUtil.java

/**
 * xml字符串转java对象
 * @param xmlString xml字符串
 * @param clazz 要转的bean.Class
 * @param  泛型
 *
 * @return T
 */
 public static <T> T xmlToBean(String xmlString, Class<T> clazz) throws Exception{
     XMLInputFactory factory = XMLInputFactory.newInstance();
     InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
     XMLEventReader someSource = factory.createXMLEventReader(stream);

     JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
     Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
     JAXBElement<T> userElement = jaxbUnmarshaller.unmarshal(someSource, clazz);
     return userElement.getValue();
 }


/**
 * bean对象转xml字符串
 * @param obj bean对象
 * @param clazz 要转的bean.Class
 *
 * @return object
 */
public static String beanToXml(Object obj, Class<?> clazz) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(clazz);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
    StringWriter writer = new StringWriter();
    marshaller.marshal(obj, writer);
    return writer.toString();
}


/**
 * xml字符串转Object对象
 * @param xmlString xml字符串
 * @param load 要转的bean.Class
 *
 * @return object
 */
public static Object xmlToObject(String xmlString, Class<?> clazz) throws JAXBException, IOException {
    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Object object = unmarshaller.unmarshal(new StringReader(xmlStr));
    return object;
}

你可能感兴趣的:(工具,xml,java)