4

I have an XML file which contains an element with special characters or escape characters in it. When I unmarshall this file into a Java object, JAXB automatically escapes these characters. However I do not want them to be escaped and the object should be populated with whatever value is present in the XML file. Snippet of my XML file looks something like this:

            <Order>
                  <name>Order One &gt;</name>
                  <price>50</price>
            <Order>

My JAXB Order class looks like below:

            @XmlAccessorType(XmlAccessType.FIELD)
            @XmlRootElement(name = "Order")
            public class Order{

                 @XmlElement
                 private String name;

                 @XmlElement
                 private String price;

                 //skipping getter and setter for brevity

On unmarshalling , Order class object's name field has value "Order one >" whereas I want it to be "Order One &gt;" as that is the requirement.

I am aware of the solution of putting this value within CDATA so that it doesn't get escaped however the XML file I am unmarshalling is from an outside source and I have no control over the file. I read about a solution on SO where it was suggested of looking for '&' and replacing it. But that solution doesnt look generic and wont apply to all scenarios. Unmarshalling XML with JAXB without unescaping characters

I am new to the world of JAXB and trying to find my feet. What I am trying to do might have been done before but I haven't found a solution for doing it. There are several solutions available on SO about escaping characters with JAXB however almost all talk about marshalling. Any help would be appreciated.

Community
  • 1
  • 1
LearnToLive
  • 462
  • 9
  • 25

1 Answers1

0

You won't be able to do this directly with JAXB. At the very least the MOXy and RI implementations of JAXB leverage an underlying parser to process the XML. By the time they get the data it has already been unescaped. You should look for a SAX or StAX parser that allows unescaping to be disabled and use that with JAXB to get the behaviour you are looking for.

Alternatively you could implement an XmlAdapter that re-escapes the characters on the unmarshal an unescaped them on the marshal.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Blaise - Thanks for your time. Are you suggesting creating a default handler to escape characters and passing it to SAX parser or is there some property which I can set on SAX parser which will help me achieve the desired result. I am using JAXBContext to create the unmarshallerHandler and passing it to the SAXParser. – LearnToLive Feb 23 '14 at 08:20