JAVA工具类总结——xml字符串与对象的转换

文章目录

  • 1. xml工具类代码
  • 2. 使用方法
    • 2.1 xml报文示例
    • 2.2 对象xml注解的添加
    • 2.3 xml转对象的示例
    • 2.4 对象转xml的示例

1. xml工具类代码

  先贴上工具类代码。如下:

package znxd.lxynzl.bank.base;

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;

/**
 * xml解析工具类
 */
public class XmlUtils {
    /**
     * xml字符串转对象
     * @param clazz
     * @param xmlStr
     * @return
     */
    public static Object xmlStrToObject(Class clazz, String xmlStr) {
        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return xmlObject;
    }

    /**
     * 对象转xml字符串
     * @param obj
     * @param load
     * @return
     * @throws JAXBException
     */
    public static String objectToXmlStr(Object obj,Class<?> load){
        String result = "";
        try{
            JAXBContext context = JAXBContext.newInstance(load);
            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);
            result = writer.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}

2. 使用方法

2.1 xml报文示例

  首先,要有个xml报文,我找了个复杂点的,如下:

	
	<bocb2e version="100" security="true" lang="chs">
	<head>
	<termid>E127000000001termid>
	<trnid>20060704001trnid>
	<custid>12345678custid>
	<cusopr>BOCcusopr>
	<trncod>b2e0001trncod>
	head>
	<trans>
	<trn-b2e0001-rq>
	<b2e0001-rq>
	<custdt>20060704091000custdt>
	<oprpwd>88888888oprpwd>
	<ceitinfo>MIIE9AYJKoZIhvcNA……ceitinfo>
	b2e0001-rq>
	trn-b2e0001-rq>
	trans>
	bocb2e>

  大体可以看出来,首先最外边是根标签 ,下一级是,然后再往里一层层的。

2.2 对象xml注解的添加

  既然要xml与对象转换,那自然要先创建对象,因为按照上边的报文来看,每一层即一个对象,这样的话就会有好几个对象。
  虽然多,但是并不复杂,只需要把xml标签对应上即可,另外该工具不需要额外引入依赖,属于java自己的工具。

主要就三个注解,我理解的意思如下:
  @XmlRootElement表示当前标签的名字
  @XmlType表示当前对象里,含有的下级标签对应的对象的属性名。
  @XmlElement表示当前对象的属性,对应到xml里的标签名。

需要创建的对象具体如下:

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"head","trans"})
@XmlRootElement(name="bocb2e")
public class BOCSignRequestXml {

    private SignRequestHead head;
    
    private SignRequestTrans trans;
   //省略get set方法
}

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 签名请求head体
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="head")
public class SignRequestHead {

    @XmlElement(name="termid")
    private String termid;

    @XmlElement(name="trnid")
    private String trnid;

    @XmlElement(name="custid")
    private String custid;

    @XmlElement(name="cusopr")
    private String cusopr = "BOC";

    @XmlElement(name="trncod")
    private String trncod = "b2e0001";
    //省略get set方法
}

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"trnB2e0001Rq"})
@XmlRootElement(name="trans")
public class SignRequestTrans {

    @XmlElement(name="trn-b2e0001-rq")
    private TrnB2e0001Rq trnB2e0001Rq;

   //省略get set方法
}


import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"b2e0001Rq"})
@XmlRootElement(name="trn-b2e0001-rq")
public class TrnB2e0001Rq {

    @XmlElement(name="b2e0001-rq")
    private B2e0001Rq b2e0001Rq;

    //省略get set方法
}


import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="b2e0001-rq")
public class B2e0001Rq {

    @XmlElement(name="custdt")
    private String custdt;

    @XmlElement(name="oprpwd")
    private String oprpwd;

    @XmlElement(name="ceitinfo")
    private String ceitinfo;

    //省略get set方法
}

2.3 xml转对象的示例

  xml字符串转对象的测试方法如下:

 public static void main(String[] args){
        //签到
        String xmlStr ="" +
                "" +
                "" +
                "E127000000001" +
                "20060704001" +
                "12345678" +
                "BOC" +
                "b2e0001" +
                "" +
                "" +
                "" +
                "" +
                "20060704091000" +
                "88888888" +
                "MIIE9AYJKoZIhvcNA……" +
                "" +
                "" +
                "" +
                "";

        BOCSignRequestXml requestXml = (BOCSignRequestXml) XmlUtils.xmlStrToObject(BOCSignRequestXml.class,xmlStr);
        System.out.println(requestXml.getTrans().getTrnB2e0001Rq()
        .getB2e0001Rq().getOprpwd());
        System.out.println(requestXml.getHead().getTrncod());
        

  执行后的结果如下:

	88888888
	b2e0001

2.4 对象转xml的示例

  对象转xml字符串的测试方法如下:

    public static void main(String[] args){
        BOCSignRequestXml requestXml1 = new BOCSignRequestXml();
        SignRequestHead requestHead = new SignRequestHead();
        requestHead.setCusopr("2222");
        requestXml1.setHead(requestHead);
        String xmlStrTo =  XmlUtils.objectToXmlStr(requestXml1,BOCSignRequestXml.class);
        System.out.println(xmlStrTo);
    }

  执行后的结果如下:

	<?xml version="1.0" encoding="GBK" standalone="yes"?>
	<bocb2e>
	    <head>
	        <cusopr>2222</cusopr>
	        <trncod>b2e0001</trncod>
	    </head>
	</bocb2e>

  以上即是xml字符串与对象之间的转换方法。亲测,灰常好用。

你可能感兴趣的:(java,xml字符串与对象的转换,java语言xml与对象转换)