Jaxb cannot directly generate xml with CDATA region, and a lotArticle, The test class is as follows:
-------- Class (a class found from the internet )------
Package com;
Import javax. xml. Bind. annotation. xmlrootelement;
@ Xmlrootelement
Public class people {
Public String id = "001 ";
Public string name = "grey Wolf ";
Public int age = 26;
}
------------ Learn from jaxbcdatasample. Java ----------------
Package com;
Import java. Io. file;
Import java. Io. printstream;
Import java. Io. stringwriter;
Import javax. xml. Bind. jaxbcontext;
Import javax. xml. Bind. marshaller;
Import javax. xml. Bind. unmarshaller;
Import javax. xml. Transform. Sax. saxresult;
Import org. Apache. xml. serialize. outputformat;
Import org. Apache. xml. serialize. xmlserializer;
Public class jaxbcdatasample {
@ suppresswarnings ("deprecation")
Public static void main (string [] ARGs) throws exception {
// unmarshal a doc
jaxbcontext JC = jaxbcontext. newinstance (people. class);
unmarshaller u = JC. createunmarshaller ();
file F = new file ("src/people. XML ");
Object o = u. unmarshal (f);
// Create a jaxb using aller
Extends aller M = JC. createmarshaller ();
M. setproperty (marshaller. jaxb_encoding, "UTF-8 ");
M. setproperty (marshaller. jaxb_formatted_output, true );
M. setproperty (marshaller. jaxb_formatted_output, false );
// Get an Apache xmlserializer configured to generate CDATA
Xmlserializer serializer = getxmlserializer ();
// Marshal using the Apache xmlserializer
Saxresult result = new saxresult (serializer. ascontenthandler ());
M. Marshal (O, result );
// System. Out. println ();
// M. getnode (O );
// System. Out. println ("====" + contenthandler );
}
Private Static xmlserializer getxmlserializer (){
// Configure an outputformat to handle CDATA
Outputformat of = new outputformat ();
// Specify which of your elements you want to be handled as CDATA.
// The use of the '^' between the namespaceuri and the localname
// Seems to be an implementation detail of the xerces code.
// When processing XML that doesn't use namespaces, simply omit
// Namespace prefix as shown in the third cdataelement below.
Of. setcdataelements (
New String [] {"^ ID ",//
"^ Name ",//
"^ Age "});//
// Set any other options you 'd like
Of. setpreservespace (true );
Of. setindenting (true );
Stringwriter writer = new stringwriter ();
// Create the serializer
Xmlserializer serializer = new xmlserializer ();
Serializer. setoutputbytestream (system. Out );
Return serializer;
}
}< br> -----------------------------------------------------
the final running result is printed to the console: