avatar

xml解析--JaxbUtil

主要介绍使用jaxb对xml进行解析, 互转.

jaxb 是相对较多的xml工具, 只需要在javaBean的属性上添加相应注解, 就可以使用工具进行解析. 具体使用过程如下:

1. 编写javaBean并添加注解

使用过程中一般常用@XmlRootElement, @XmlAccessorType, @XmlElement, @XmlAttribute四个注解, 其余使用方式可以再自行深入研究.

@XmlRootElement: 根元素
@XmlAccessorType: java对象生成xml文件时对java对象属性的访问方式
属性为XmlAccessType.FIELD 指java所有成员变量
@XmlElement: 子节点, name 可指定节点名
@XmlAttribute: 映射为xml文件的属性, name 可指定属性名

javaBean:

@Data
@XmlRootElement(name = "alipay")
@XmlAccessorType(XmlAccessType.FIELD)
class AliPayXml {

@XmlElement(name = "alipay_buyer_login_id" )
private String buyerLoginId;

@XmlElement(name = "alipay_buyer_user_id")
private String buyerUserId;
}
2. 使用 JaxbUtil

JaxbUtil代码

package com.liuzhihang.tool.xml;

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;

/**
* Jaxb 工具
*
* @author liuzhihang
* @date 2017/11/28 19:13
*/
public class JaxbUtil {

private static final String CHARTSET = "UTF-8";

public static String bean2Xml(Object obj) throws JAXBException {
return bean2Xml(obj, CHARTSET);
}

public static String bean2Xml(Object obj, String chartset) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, chartset);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.getBuffer().toString();
}

public static <T> T xml2Bean(String xmlString, Class<T> clazz) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
T t = (T) unmarshaller.unmarshal(new StringReader(xmlString));
return t;
}
}
3. 测试代码

待测试字符串: xmlStr

<alipay>
<alipay_buyer_login_id>176****3035</alipay_buyer_login_id>
<alipay_buyer_user_id>2088912868994947</alipay_buyer_user_id>
</alipay>

测试代码:


/**
* @Description:
* @Author: liuzhihang
* @Date: 2017/12/17 23:11
*/
public class JaxbTest {

public static void main(String[] args) throws JAXBException {
String aliPayXmlStr = "<alipay>\n" +
" <alipay_buyer_login_id>176****3035</alipay_buyer_login_id>\n" +
" <alipay_buyer_user_id>2088912868994947</alipay_buyer_user_id>\n" +
"</alipay>";

AliPayXml aliPayXml = JaxbUtil.xml2Bean(aliPayXmlStr, AliPayXml.class);
System.out.println(JSON.toJSONString(aliPayXml));
}
}

测试结果:

打印的为json格式结果, 可debugger查看. 同样也可以将javaBean转换为xmlStr

{"buyerLoginId":"176****3035","buyerUserId":"2088912868994947"}
文章作者: liuzhihang
文章链接: https://liuzhihang.com/2017/12/17/xml-parsing-jaxbutil.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Notes

评论