对象装xml中CDATA问题
前端时间做沃尔玛刊登的数据拼接时,遇到了对象转xml格式问题。
对象转xml是用以下方法:(将 < 换成< 这种写法是没办法的办法,如果有好的方法可以甩给我,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博客
还没有评论,来说两句吧...