JAXB sorts and unpacks CDATA

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>

My program should unleash this JAXB, do some processing, and finally marshall back to xml. When I finally marshaled JAXB objects in xml, I get plain text without the prefix CDATA. But in order to keep xml intact, I need to return xml with CDATA prefix. JAXB does not seem to support this directly. Is there any way to achieve this?

+2
source share
3 answers

CDATA or not, this should not be a problem, because when you exit JAXB it will be escaped if necessary.

+1
source

, , , . beans xjc, @XmlCData .

: http://javacoalface.blogspot.pt/2012/09/outputting-cdata-sections-with-jaxb.html

:

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));

. , , , , .

+1

. EclipseLink JAXB (MOXy) JAXB 2 (JSR-222).

MOXy @XmlCDATA, node CDATA:

package blog.cdata;

import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;

@XmlRootElement(name="c")
public class Customer {

   private String bio;

   @XmlCDATA
   public void setBio(String bio) {
      this.bio = bio;
   }

   public String getBio() {
      return bio;
   }

}

0
source

All Articles