快花费一天的时间了,终于找到解决方法,简单记下来
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://*.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);
}
}