I have an Object that is being marshalled to XML using JAXB. One element contains a String that includes quotes ("). The resulting XML has "
where the " existed.
Even though this is normally preferred, I need my output to match a legacy system. How do I force JAXB to NOT convert the HTML entities?
--
Thank you for the replies. However, I never see the handler escape() called. Can you take a look and see what I'm doing wrong? Thanks!
package org.dc.model;
import java.io.IOException;
import java.io.Writer;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.dc.generated.Shiporder;
import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler;
public class PleaseWork {
public void prettyPlease() throws JAXBException {
Shiporder shipOrder = new Shiporder();
shipOrder.setOrderid("Order's ID");
shipOrder.setOrderperson("The woman said, \"How ya doin & stuff?\"");
JAXBContext context = JAXBContext.newInstance("org.dc.generated");
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(CharacterEscapeHandler.class.getName(),
new CharacterEscapeHandler() {
@Override
public void escape(char[] ch, int start, int length,
boolean isAttVal, Writer out) throws IOException {
out.write("Called escape for characters = " + ch.toString());
}
});
marshaller.marshal(shipOrder, System.out);
}
public static void main(String[] args) throws Exception {
new PleaseWork().prettyPlease();
}
}
--
The output is this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<shiporder orderid="Order's ID">
<orderperson>The woman said, "How ya doin & stuff?"</orderperson>
</shiporder>
and as you can see, the callback is never displayed. (Once I get the callback being called, I'll worry about having it actually do what I want.)
--
Solution my teammate found:
PrintWriter printWriter = new PrintWriter(new FileWriter(xmlFile));
DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", DumbEscapeHandler.theInstance);
marshaller.marshal(request, dataWriter);
Instead of passing the xmlFile to marshal(), pass the DataWriter which knows both the encoding and an appropriate escape handler, if any.
Note: Since DataWriter and DumbEscapeHandler are both within the com.sun.xml.internal.bind.marshaller package, you must bootstrap javac.