How to handle special characters while unmarshalling xml in JAXB

2031
March 28, 2017, at 9:34 PM

my test xml content

    <p id="033" num="03">geopotent change&#x2 high.</p>

And I run Jaxb Unmarshalling, but I'm getting exception

    09:58:43.748 ERROR [main][net.ServiceImpl] Parsing Error: 
    javax.xml.bind.UnmarshalException- with linked exception:    
    [javax.xml.stream.XMLStreamException: ParseError at [row,col]:
    [161,306]Message: String "&#]

my Jaxb unmarshal source is

    JAXBContext jaxbContext = JAXBContext.newInstance(CnDocument.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    document = (CnDocument) jaxbUnmarshaller.unmarshal(xmlFile);

How can I escape those characters? (&#x2)

Answer 1

You get a JAXB parse error because your XML content is not well-formed. It should be &#x2; (with semicolon), not &#x2.

Answer 2

<p id="033" num="03">geopotent change&#x2 high.</p> is not valid XML. Either "escape" the ampersand character using &amp; or make the character reference complete by adding a semicolon: &#x2;.

Answer 3

This is one way you can do:

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
public class XmlCharacterHandler implements CharacterEscapeHandler {
    public void escape(char[] buf, int start, int len, boolean isAttValue,
            Writer out) throws IOException {
        StringWriter buffer = new StringWriter();
        for (int i = start; i < start + len; i++) {
            buffer.write(buf[i]);
        }
        String st = buffer.toString();
        if (!st.contains("CDATA")) {
            st = buffer.toString().replace("&", "&amp;").replace("<", "&lt;")
                .replace(">", "&gt;").replace("'", "&apos;")
                .replace("\"", "&quot;");
        }
        out.write(st);
        System.out.println(st);
    }
}

While marshaling :

marshaller.setProperty(CharacterEscapeHandler.class.getName(),
                new XmlCharacterHandler());
READ ALSO
Jenkins fails due to NoClassDefFoundError: org/sonatype/aether/version/VersionConstraint

Jenkins fails due to NoClassDefFoundError: org/sonatype/aether/version/VersionConstraint

I'm attempting to set up Jenkins on my server but after building the job things turn southYou can view the console here: http://ci

419
Android: return null in front of API response

Android: return null in front of API response

I am making a Call to API which saves location and returns the values which i have passed to itBut In the response log it is showing null before the API response result

350
Spring Data Jpa Query dsl with fetch join

Spring Data Jpa Query dsl with fetch join

Is it possible to specify Join Fetch when using QueryDsl and Spring Data Repository?

457