对象装xml中CDATA问题

前端时间做沃尔玛刊登的数据拼接时,遇到了对象转xml格式问题。

对象转xml是用以下方法:(将 &lt; 换成< 这种写法是没办法的办法,如果有好的方法可以甩给我,jdk1.8版本 )

public String convertToXMLCDATA(Object o) {
        try {
            JAXBContext context = JAXBContext.newInstance(o.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter sw = new StringWriter();
            marshaller.marshal(o, sw);
            marshaller.marshal(o, System.out);
            return sw.toString().replace("<", "<").replace(">", ">");
        } catch (JAXBException e) {
            e.printStackTrace();
        }

        return null;
    }

但是沃尔玛需要的格式是:

<longDescription><![CDATA[<li>1rrrr23</li>]]></longDescription>

相对于html代码来说多了一个CDATA,此时需要添加一个xml适配器。xmlJavaTypeAdapter.

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class CDataAdapter extends XmlAdapter<String, String> {
	public String unmarshal(String v) throws Exception {
		return "<![CDATA[" + v + "]]>";
	}

	public String marshal(String v) throws Exception {
		return "<![CDATA[" + v + "]]>";
	}
}

在需要的字段上添加注解

@XmlJavaTypeAdapter(CDataAdapter.class)
	protected String longDescription;


微笑 微笑 微笑

个人主页 ITDragon博客







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值