微信小程序入门二 ------对象装xml中CDATA问题

http://blog.csdn.net/qq_19558705/article/details/59483546

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

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

 

[java] view plain copy
 
  1. public String convertToXMLCDATA(Object o) {  
  2.         try {  
  3.             JAXBContext context = JAXBContext.newInstance(o.getClass());  
  4.             Marshaller marshaller = context.createMarshaller();  
  5.             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
  6.             StringWriter sw = new StringWriter();  
  7.             marshaller.marshal(o, sw);  
  8.             marshaller.marshal(o, System.out);  
  9.             return sw.toString().replace("<", "<").replace(">", ">");  
  10.         } catch (JAXBException e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.   
  14.         return null;  
  15.     }  

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

 

 

[html] view plain copy
 
  1. <longDescription><![CDATA[<li>1rrrr23</li>]]></longDescription>  

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

 

 

[java] view plain copy
 
  1. import javax.xml.bind.annotation.adapters.XmlAdapter;  
  2.   
  3. public class CDataAdapter extends XmlAdapter<String, String> {  
  4.     public String unmarshal(String v) throws Exception {  
  5.         return "<![CDATA[" + v + "]]>";  
  6.     }  
  7.   
  8.     public String marshal(String v) throws Exception {  
  9.         return "<![CDATA[" + v + "]]>";  
  10.     }  
  11. }  

在需要的字段上添加注解

 

 

[java] view plain copy
 
  1. @XmlJavaTypeAdapter(CDataAdapter.class)  
  2.     protected String longDescription;  
posted @ 2018-01-22 19:25  yangchunlong  阅读(288)  评论(0)    收藏  举报