用jaxb通过XSD生成Java类的CDATA的处理

快花费一天的时间了,终于找到解决方法,简单记下来

1. 开始通过:http://theopentutorials.com/tutorials/java/jaxb/jaxb-marshalling-and-unmarshalling-cdata-block/ 这篇文章的方式解决,cdata是输出正确了,但是其他元素中不是cdata,但是含有特殊字符,比如&,&没有转义

2. http://blog.mi-ernst.de/2012/05/04/jaxb-and-cdata-sections/,把所有元素中含有特殊字符的全部转换成cdata了

3. http://stackoverflow.com/questions/13183510/moxys-xmlcdata-seems-to-have-no-affect,解决文件

加入包eclipselink.jar,下载:http://mirrors.ustc.edu.cn/eclipse/rt/eclipselink/releases/2.5.0/eclipselink-2.5.0.v20130507-3faac2b.zip

把需要转换成cdata的属性注解起来:

import org.eclipse.persistence.oxm.annotations.XmlCDATA;

/**
 * <p>anonymous complex type的 Java 类。
 * 
 * <p>以下模式片段指定包含在此类中的预期内容。
 * 
 * <pre>
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="head" type="{http://www.chinatax.gov.cn/spec/}headType"/>
 *         <element name="body" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "head",
    "body"
})
@XmlRootElement(name = "service")
public class Service {

    @XmlElement(required = true)
    protected HeadType head;
    @XmlElement(required = true)
    @XmlCDATA
    protected String body;
注意注解类是
org.eclipse.persistence.oxm.annotations.XmlCDATA
建文件jaxb.properties放到java类路径下,就是和java类一个路径

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory


测试:

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyObject.class);

        MyObject myObject = new MyObject();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(myObject, System.out);
    }

}



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值