Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling XML escape characters (e.g. quotes) using JAXB Marshaller

I need to serialize an XML java object to a XML file using the JAXB Marshaller (JAXB version 2.2). Now in the xml object, I have a tag which contains String value such that:

"<"tagA>
**"<"YYYYY>done"<"/YYYYY>**
"<"/tagA>

Now as you can see that this string value again contains tags. I want this to be written in the same way in the xml file.

But JAXB Marshaller converts these values such as:

"&"lt;YYYYY"&"gt;"&"#xD;done ...& so on

I am not able to treat these escape characters separately using JAXB 2.2 Is it possible anyways?

Any help in this regard will be great..

Thanks in advance, Abhinav Mishra

like image 948
javdev Avatar asked Dec 14 '10 04:12

javdev


1 Answers

There is one simpler way. First use custom escape sequence:

m.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() {
    @Override
    public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
        out.write( ch, start, length ); 
    }
}); 

Then marshal it to a String like mentioned below

StringWriter writer = new StringWriter();
m.marshal(marshalObject, writer);

and then create a document object from the writer mentioned below

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( writer.toString() ) );
Document doc = builder.parse( is );

escape characters issue will be resolved

like image 50
preetham Avatar answered Sep 28 '22 05:09

preetham