JAXB编组和解组CDATA

编程入门 行业动态 更新时间:2024-10-23 01:41:54
本文介绍了JAXB编组和解组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.

在寻找一个好的解决方案后,我终于找到了这个发布: javacoalface.blogspot.pt/2012 /09/outputting-cdata-sections-with-jaxb.html

After looking a while for a good solution I finally found this post: 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

本文发布于:2023-11-22 15:08:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JAXB   CDATA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!