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

后端 未结 14 1991
情深已故
情深已故 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条回答
  •  被撕碎了的回忆
    2020-11-29 09:46

    I would advise against using CharacterEscapeHandler for the reasons mentioned above (it's an internal class). Instead you can use Woodstox and supply your own EscapingWriterFactory to a XMLStreamWriter. Something like:

    XMLOutputFactory2 xmlOutputFactory = (XMLOutputFactory2)XMLOutputFactory.newFactory();
    xmlOutputFactory.setProperty(XMLOutputFactory2.P_TEXT_ESCAPER, new EscapingWriterFactory() {
    
        @Override
        public Writer createEscapingWriterFor(Writer w, String enc) {
            return new EscapingWriter(w);
        }
    
        @Override
        public Writer createEscapingWriterFor(OutputStream out, String enc) throws UnsupportedEncodingException {
            return new EscapingWriter(new OutputStreamWriter(out, enc));
        }
    
    });
    
    marshaller.marshal(model, xmlOutputFactory.createXMLStreamWriter(out);
    

    An example of how to write an EscapingWriter can be seen in CharacterEscapingTest.

提交回复
热议问题