JAXB编组和解组CDATA [英] JAXB marshalling and unmarshalling CDATA
问题描述
我有一个要求,我有这样的XML
I have a requirement in which i have XML like this
<programs>
<program>
<name>test1</name>
<instr><![CDATA[ some string ]]></instr>
</program>
<program>
<name>test2</name>
<instr><![CDATA[ some string ]]></instr>
</program>
</programs>
我的程序需要将其解组为JAXB,进行一些处理,最后再编组回xml。当我最终将JAXB对象编组为xml时,我得到没有CDATA前缀的纯文本。但为了保持xml完整,我需要使用CDATA前缀获取xml。似乎JAXB不直接支持这一点。有没有办法实现这个目标?
My program needs to unmarshal this to JAXB, do some processing and finally marshall back to xml. When I finally marshall the JAXB objects to xml, i get the as plain text without CDATA prefix. But to keep the xml intact I need to get the xml back with CDATA prefix. It seems JAXB doesnt suppor this directly. Is there a way to achieve this?
推荐答案
我也遇到了同样的问题,在查看时我发现了这篇文章。因为我用xjc生成我的bean,所以我不想在生成的代码中添加@XmlCData。
I've also had the same problem and while looking in SO I found this post. Since I'm generating my beans with xjc I did not want to add a @XmlCData in the generated code.
在寻找一个好的解决方案后,我终于找到了这个发布: http://javacoalface.blogspot.pt/2012 /09/outputting-cdata-sections-with-jaxb.html
After looking a while for a good solution I finally found this post: http://javacoalface.blogspot.pt/2012/09/outputting-cdata-sections-with-jaxb.html
其中包含以下示例代码:
Which contains the following example code:
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
Document document =
docBuilderFactory.newDocumentBuilder().newDocument();
// Marshall the feed object into the empty document.
jaxbMarshaller.marshal(jaxbObject, document);
// Transform the DOM to the output stream
// TransformerFactory is not thread-safe
StringWriter writer = new StringWriter();
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer nullTransformer = transformerFactory.newTransformer();
nullTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
nullTransformer.setOutputProperty(
OutputKeys.CDATA_SECTION_ELEMENTS,
"myElement myOtherElement");
nullTransformer.transform(new DOMSource(document),
new StreamResult(writer));
它对我来说非常好。希望它能帮助其他人登陆这个页面,寻找同样的东西。
It works pretty fine for me. Hope it helps others that land in this page looking for the same thing I was.
这篇关于JAXB编组和解组CDATA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!