java对象数据转xml文件(加<![CDATA[]]>)[注解方式]

本文详细介绍了如何将Java对象转换为XML文件,并记录了一系列注解的使用方法,以及解决XML特殊字符转义问题的技巧。

java对象数据转xml文件

    这种操作一般发生在导出文件,我在这里记录一下这一系列注解的使用,还有我遇到的问题及解决方法;
    问题:对象属性中有可能存在计算逻辑'<'或'>',而在xml文件中这两个符号是不合法的,会转换为&lt和&gt,这样数据就'坏'了,所以<![CDATA[]]>的加入是非常有必要的!

需要导入类

1.这是在你需要导出的实体类中用到的(一般都是DTO[扩展类])
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
2.这是解决<,>两个符号自动转化的工具类用到的
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

注解的使用

1.@XmlRootElement,用于类级别的注解,对应xml的跟元素。通过name属性定义这个根节点的名称。
2.@XmlAccessorType,定义映射这个类中的何种类型都需要映射到xml。(如果不存在@XmlAccessorType,默认使用XmlAccessType.PUBLIC_MEMBER注解)
  参数:XmlAccessType.FIELD: java对象中的所有成员变量。
  XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量。
  XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量。
  XmlAccessType.NONE: java对象的所有属性都不映射为xml的元素。
3.@XmlAttribute,用于把java对象的属性映射为xml的属性,并可通过name属性为生成的xml属性指定别名。
4.@XmlElement,指定一个字段或get/set方法映射到xml的节点。通过name属性定义这个根节点的名称。
5.@XmlElementWrapper,为数组或集合定义一个父节点。通过name属性定义这个父节点的名称。

xml,javaBeen的相互装换

public class JaxbUtil
{

    /**
     * 日志
     */
    private static final Log _logger = LogFactory.getLog (JaxbUtil.class);

    public static String convertToXml (Object obj)
    {
        return convertToXml (obj, "UTF-8");
    }

    /**
     * JavaBean转换成xml
     * 
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXml (Object obj, String encoding)
    {
        String result = null;
        try
        {
            JAXBContext context = JAXBContext.newInstance (obj.getClass ());
            Marshaller marshaller = context.createMarshaller ();
            marshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty (Marshaller.JAXB_ENCODING, encoding);
            StringWriter writer = new StringWriter ();
            marshaller.marshal (obj, writer);
            result = writer.toString ();
        }
        catch (Exception ex)
        {
            _logger.error (ex.getMessage (), ex);
        }
        return result;
    }

    /**
     * xml转换成JavaBean
     * 
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings ("unchecked")
    public static <T> T converyToJavaBean (String xml, Class <T> c)
    {
        T t = null;
        try
        {
            JAXBContext context = JAXBContext.newInstance (c);
            Unmarshaller unmarshaller = context.createUnmarshaller ();
            t = (T) unmarshaller.unmarshal (new StringReader (xml));
        }
        catch (Exception ex)
        {
            _logger.error (ex.getMessage (), ex);
        }
        return t;
    }

}

解决保护数据问题的工具类

public class CDataAdapter extends XmlAdapter <String, String>
{
    @Override
    public String marshal (String v) throws Exception
    {
        return "<![CDATA[" + v + "]]>";
    }
    @Override
    public String unmarshal (String v) throws Exception
    {
        if ("<![CDATA[]]>".equals (v))
        {
            return "";
        }
        String v1 = null;
        String v2 = null;
        String subStart = "<![CDATA[";
        int a = v.indexOf (subStart);
        if (a >= 0)
        {
            v1 = v.substring (subStart.length (), v.length ());
        }
        else
        {
            return v;
        }
        String subEnd = "]]>";
        int b = v1.indexOf (subEnd);
        if (b >= 0)
        {
            v2 = v1.substring (0, b);
        }
        return v2;
    }

}

对应实例

定义类

@XmlAccessorType (XmlAccessType.FIELD)
@XmlRootElement
@XmlType (name = "indicatorDefine", propOrder =
{ "indCode", "indDescs", "indTypeCode", "monTableName", "monTableDescs", "monTableFieldName", "monTableFieldDescs",
  "validateType", "validateDescs", "validateScript", "validateMethod", "relateTable", "relateScript", "stabilityIdx",
  "minValue", "maxValue", "enableStatus" })
public class IndicatorDefineExportDto implements Serializable
{
    private static final long serialVersionUID = 4903249232957489027L;
    @XmlElement (name = "indCode")
    private String indCode;
    @XmlElement (name = "indDescs")
    private String indDescs;
    @XmlElement (name = "indTypeCode")
    private String indTypeCode;
    @XmlElement (name = "monTableName")
    private String monTableName;
    @XmlElement (name = "monTableDescs")
    private String monTableDescs;
    @XmlElement (name = "monTableFieldName")
    private String monTableFieldName;
    @XmlElement (name = "monTableFieldDescs")
    private String monTableFieldDescs;
    @XmlElement (name = "validateType")
    private String validateType;
    @XmlElement (name = "validateDescs")
    private String validateDescs;
    @XmlJavaTypeAdapter (CDataAdapter.class)//这里是该属性需要加<![CDATA[]]>防止转换的注解
    @XmlElement (name = "validateScript")
    private String validateScript;
    @XmlElement (name = "validateMethod")
    private String validateMethod;
    @XmlJavaTypeAdapter (CDataAdapter.class)//这里是该属性需要加<![CDATA[]]>防止转换的注解
    @XmlElement (name = "relateTable")
    private String relateTable;
    @XmlElement (name = "relateScript")
    private String relateScript;
    @XmlElement (name = "stabilityIdx")
    private String stabilityIdx;
    @XmlElement (name = "minValue")
    private String minValue;
    @XmlElement (name = "maxValue")
    private String maxValue;
    @XmlElement (name = "enableStatus")
    private String enableStatus;
    //get,set方法省略
    }

@XmlAccessorType (XmlAccessType.FIELD)
@XmlRootElement (name = "IndicatorDefineData")
@XmlType (propOrder =
{ "indicatorDefines" })
public class IndicatorDefines implements Serializable
{

    /**
     * serialVersionUID:TODO
     * 
     * @since Ver 1.1
     */
    private static final long serialVersionUID = 3140176739363502638L;

    @XmlElementWrapper (name = "indicatorDefines")
    @XmlElement (name = "indicatorDefine")
    private List <IndicatorDefineExportDto> indicatorDefines;

使用

List <IndicatorDefineExportDto> indicatorDefineExportDtos = new ArrayList <IndicatorDefineExportDto> ();
IndicatorDefineExportDto indicatorDefineExportDto = new IndicatorDefineExportDto ();
//省略查询数据操作
//indicatorDefineInfos--查询到的数据
 for (IndicatorDefine indicatorDefine : indicatorDefineInfos){
 IndicatorDefineExportDto indicatorDefineExportDto = new IndicatorDefineExportDto ();
 //省略...
 //将indicatorDefine数据赋值到indicatorDefineExportDto 属性上
 indicatorDefineExportDtos.add (indicatorDefineExportDto);
 }
 indicatorDefines.setIndicatorDefines (indicatorDefineExportDtos);
 //生成xml内容
 String xmlContent = JaxbUtil.convertToXml (indicatorDefines);
 //以下省略...就是将文件传到前台

效果

public int getMatchedCombinedRatioServiceCount(GrpOrgInfoSettingDomain domain){ return grpOrgInfoSettingDao.getMatchedCombinedRatioServiceCount(domain); } <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.foresealife.newglschannel.grp.dao.GrpOrgInfoSettingDao"> <!-- 查询sql结果与java model映射--> <resultMap id="CombinedRatioResultMap" type="com.foresealife.newglschannel.grp.domain.GrpOrgInfoSettingDomain"> <result property="organCode" column="ORGAN_CODE"/> <result property="organName" column="ABBR_NAME"/> <result property="ym" column="YM"/> <result property="setValue" column="SET_VALUE"/> </resultMap> <!-- 公用查询sql--> <sql id="CombinedRatioQuery"> <![CDATA[ select ois.organ_code, to_char(ois.start_date, 'yyyy') ym, ois.set_value,tco.abbr_name from T_GRP_ORG_INFO_SETTING ois,t_company_organ tco where ois.set_type = '1' and ois.organ_code=tco.organ_code ]]> <if test= "organId != null and organId != ''"> and tco.organ_id in (select t.organ_id from t_company_organ t where t.status = 1 start with t.organ_id = '1' connect by PRIOR t.organ_id = t.parent_id) </if> <if test= "ym != null and ym != ''"> and ois.start_date = to_date(#{ym} || '0101', 'yyyymmdd') </if> </sql> <select id="combinedRatioReport" parameterType="com.foresealife.newglschannel.grp.domain.FileDownForm" resultMap="CombinedRatioResultMap"> <include refid="CombinedRatioQuery" /> </select> <!--查询记录数--> <select id="getMatchedCombinedRatioServiceCount" parameterType="com.foresealife.newglschannel.grp.domain.GrpOrgInfoSettingDomain" resultType="java.lang.Integer" > select count(*) from ( <include refid="CombinedRatioQuery" /> ) </select> <!--分页查询--> <select id="getMatchedCombinedRatioServiceList" parameterType="com.foresealife.newglschannel.grp.domain.GrpOrgInfoSettingDomain" resultMap="CombinedRatioResultMap"> <![CDATA[ SELECT * FROM ( select rownum r, union_tb.* from ( ]]> <include refid="CombinedRatioQuery" /> <![CDATA[ ) union_tb ) WHERE r > #{startIndex} AND r <= (#{startIndex} + #{pageSize}) ]]> </select> </mapper>为什么报错Invalid bound statement (not found): com.foresealife.newglschannel.grp.dao.GrpOrgInfoSettingDao.getMatchedCombinedRatioServiceCount
最新发布
11-07
我有一个xml,这个里面的又是什么意思呢? <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zingsemi.generator.mapper.GenTableColumnMapper"> <resultMap type="GenTableColumn" id="GenTableColumnResult"> <id property="columnId" column="column_id" /> <result property="tableId" column="table_id" /> <result property="columnName" column="column_name" /> <result property="columnComment" column="column_comment" /> <result property="columnType" column="column_type" /> <result property="javaType" column="java_type" /> <result property="javaField" column="java_field" /> <result property="isPk" column="is_pk" /> <result property="isIncrement" column="is_increment" /> <result property="isRequired" column="is_required" /> <result property="isInsert" column="is_insert" /> <result property="isEdit" column="is_edit" /> <result property="isList" column="is_list" /> <result property="isQuery" column="is_query" /> <result property="queryType" column="query_type" /> <result property="htmlType" column="html_type" /> <result property="dictType" column="dict_type" /> <result property="sort" column="sort" /> <result property="createBy" column="create_by" /> <result property="createTime" column="create_time" /> <result property="updateBy" column="update_by" /> <result property="updateTime" column="update_time" /> </resultMap> <sql id="selectGenTableColumnVo"> select column_id, table_id, column_name, column_comment, column_type, java_type, java_field, is_pk, is_increment, is_required, is_insert, is_edit, is_list, is_query, query_type, html_type, dict_type, sort, create_by, create_time, update_by, update_time from gen_table_column </sql> <select id="selectGenTableColumnListByTableId" parameterType="Long" resultMap="GenTableColumnResult"> <include refid="selectGenTableColumnVo"/> where table_id = #{tableId} order by sort </select> <select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult"> select column_name, (case when (is_nullable = 'no' <![CDATA[ && ]]> column_key != 'PRI') then '1' else null end) as is_required, (case when column_key = 'PRI' then '1' else '0' end) as is_pk, ordinal_position as sort, column_comment, (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, column_type from information_schema.columns where table_schema = (select database()) and table_name = (#{tableName}) order by ordinal_position </select> <insert id="insertGenTableColumn" parameterType="GenTableColumn" useGeneratedKeys="true" keyProperty="columnId"> insert into gen_table_column ( <if test="tableId != null and tableId != ''">table_id,</if> <if test="columnName != null and columnName != ''">column_name,</if> <if test="columnComment != null and columnComment != ''">column_comment,</if> <if test="columnType != null and columnType != ''">column_type,</if> <if test="javaType != null and javaType != ''">java_type,</if> <if test="javaField != null and javaField != ''">java_field,</if> <if test="isPk != null and isPk != ''">is_pk,</if> <if test="isIncrement != null and isIncrement != ''">is_increment,</if> <if test="isRequired != null and isRequired != ''">is_required,</if> <if test="isInsert != null and isInsert != ''">is_insert,</if> <if test="isEdit != null and isEdit != ''">is_edit,</if> <if test="isList != null and isList != ''">is_list,</if> <if test="isQuery != null and isQuery != ''">is_query,</if> <if test="queryType != null and queryType != ''">query_type,</if> <if test="htmlType != null and htmlType != ''">html_type,</if> <if test="dictType != null and dictType != ''">dict_type,</if> <if test="sort != null">sort,</if> <if test="createBy != null and createBy != ''">create_by,</if> create_time )values( <if test="tableId != null and tableId != ''">#{tableId},</if> <if test="columnName != null and columnName != ''">#{columnName},</if> <if test="columnComment != null and columnComment != ''">#{columnComment},</if> <if test="columnType != null and columnType != ''">#{columnType},</if> <if test="javaType != null and javaType != ''">#{javaType},</if> <if test="javaField != null and javaField != ''">#{javaField},</if> <if test="isPk != null and isPk != ''">#{isPk},</if> <if test="isIncrement != null and isIncrement != ''">#{isIncrement},</if> <if test="isRequired != null and isRequired != ''">#{isRequired},</if> <if test="isInsert != null and isInsert != ''">#{isInsert},</if> <if test="isEdit != null and isEdit != ''">#{isEdit},</if> <if test="isList != null and isList != ''">#{isList},</if> <if test="isQuery != null and isQuery != ''">#{isQuery},</if> <if test="queryType != null and queryType != ''">#{queryType},</if> <if test="htmlType != null and htmlType != ''">#{htmlType},</if> <if test="dictType != null and dictType != ''">#{dictType},</if> <if test="sort != null">#{sort},</if> <if test="createBy != null and createBy != ''">#{createBy},</if> sysdate() ) </insert> <update id="updateGenTableColumn" parameterType="GenTableColumn"> update gen_table_column <set> column_comment = #{columnComment}, java_type = #{javaType}, java_field = #{javaField}, is_insert = #{isInsert}, is_edit = #{isEdit}, is_list = #{isList}, is_query = #{isQuery}, is_required = #{isRequired}, query_type = #{queryType}, html_type = #{htmlType}, dict_type = #{dictType}, sort = #{sort}, update_by = #{updateBy}, update_time = sysdate() </set> where column_id = #{columnId} </update> <delete id="deleteGenTableColumnByIds" parameterType="Long"> delete from gen_table_column where table_id in <foreach collection="array" item="tableId" open="(" separator="," close=")"> #{tableId} </foreach> </delete> <delete id="deleteGenTableColumns"> delete from gen_table_column where column_id in <foreach collection="list" item="item" open="(" separator="," close=")"> #{item.columnId} </foreach> </delete> </mapper>
09-18
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值