基于Xstream工具解决对象到xml文本的集合节点重复问题

前端之家收集整理的这篇文章主要介绍了基于Xstream工具解决对象到xml文本的集合节点重复问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

http://www.jb51.cc/article/p-ditrelwy-gh.html
继如上链接博客之后,具体问题的解决方

<?xml version="1.0" encoding="utf-8"?>
<root>
    <BASE_DATA>
        <USER_CODE>0001</USER_CODE>
        <USER_NAME>0001</USER_NAME>
        <ORG_CODE>010</ORG_CODE>
        <COM_CODE>010</COM_CODE>
        <ORG_NAME>010</ORG_NAME>
        <ROLE_CODE>1</ROLE_CODE>
    </BASE_DATA>  
    <Meta_DATA>
        <IMAGE_TYPES>
            <IMAGE_TYPE>021</IMAGE_TYPE>
            <IMAGE_TYPE>022</IMAGE_TYPE>
        </IMAGE_TYPES>
        <BATCH>
            <APP_CODE>A21</APP_CODE>
            <BUSI_NUM>0000**************025</BUSI_NUM>
        </BATCH>
    </Meta_DATA>
</root>
  • step1:java对象编写
public class BaseData {
    @XStreamAlias("USER_CODE")
    private String userCode;
    @XStreamAlias("USER_NAME")
    private String userName;
    @XStreamAlias("ORG_CODE")
    private String orgCode;
    @XStreamAlias("COM_CODE")
    private String comCode;
    @XStreamAlias("ORG_NAME")
    private String orgName;
    @XStreamAlias("ROLE_CODE")
    private String roleCode;

    //getter及setter
    ... ...
}

应注意的此对象的差异(对属性imageTypes的处理方式)

public class MetaData {
    @XStreamAlias("BATCH")
    private Batch batchNode;
    @XStreamAlias("IMAGE_TYPES")
    private List<String> imageTypes = new ArrayList<String>();
    @XStreamAlias("COUNT_PER_PAGE")
    private String countPerPage;
    //此处注意,针对重复命名之后转换为xml节点嵌套的解决方
    //将节点(IMAGE_TYPES)作为集合对象处理
    public void add(String imageType){
        this.imageTypes.add(imageType);
    }

    //除属性:imageTypes之外,setter及getter
    ... ...
}
public class Batch{
    @XStreamAlias("APP_CODE")
    private String appCode;
    @XStreamAlias("BUSI_NUM")

    //getter及setter
    ... ...
}
@XStreamAlias("root")
public class Query {
    @XStreamAlias("BASE_DATA")
    private BaseData baseData;
    @XStreamAlias("Meta_DATA")
    private MetaData MetaData;

    //getter及setter
    ... ...
}
......
    XStream xStream=new XStream(new DomDriver("UTF-8",new XmlFriendlyReplacer("-_","_")));
    xStream.addImmutableType(ImageTypeBean.class);
    xStream.alias("IMAGE_TYPE",String.class);
    xStream.autodetectAnnotations(true);
    String str= xStream.toXML(query);
    ......
原文链接:https://www.f2er.com/xml/297005.html

猜你在找的XML相关文章