Can I force JAXB not to convert " into ", for example, when marshalling to XML?

后端 未结 14 1971
情深已故
情深已故 2020-11-29 09:27

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 t

14条回答
  •  -上瘾入骨i
    2020-11-29 09:58

    After trying all the above solutions, finally came to the conclusion.

    your marshaling logic through the custom escape handler.

    final StringWriter sw = new StringWriter();
        final Class classType = fixml.getClass();
        final JAXBContext jaxbContext = JAXBContext.newInstance(classType);
        final Marshaller marshaller = jaxbContext.createMarshaller();
        final JAXBElement fixmsg = new JAXBElement(new QName(namespaceURI, localPart), classType, fixml);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(CharacterEscapeHandler.class.getName(), new JaxbCharacterEscapeHandler());
        marshaller.marshal(fixmsg, sw);
        return sw.toString();
    

    And the custom escape handler is as follow:

    import java.io.IOException;
    import java.io.Writer;
    
    public class JaxbCharacterEscapeHandler implements CharacterEscapeHandler {
    
        public void escape(char[] buf, int start, int len, boolean isAttValue,
                        Writer out) throws IOException {
    
                for (int i = start; i < start + len; i++) {
                        char ch = buf[i];
                        out.write(ch);
                }
        }
    }
    

提交回复
热议问题