4

I want to add a description to my place marks that is a series of html. When I run the marshaller, I get a bunch of special character strings instead of the special chars. i.e. My final file looks like CDATA&lt;html&gt; instead of CDATA<html>.

I don't want to overwrite the JAK marshaller, so I'm hoping there's a simple way to ensure my exact string is carried over to the file.

Thanks.

Joe Essey
  • 3,457
  • 8
  • 40
  • 69

2 Answers2

1

Marshaling actually escapes the special characters, " to &quot;, & to &amp; and < to &lt;.

My piece of advice would be use replace function of Strings that would actually help in reconverting the escaped characters back in the normal ones.

    try {
            StringWriter sw = new StringWriter();
            return marshaller.marshal(obj, sw);
        } catch (JAXBException jaxbe) {
            throw new XMLMarshalException(jaxbe);
        }

Using the sw object, use the sw.toString().replace() to replace the changed characters back to the original one.

This would ensure you having the things in sync of what you want like.

Hope this helps..

geocodezip
  • 158,664
  • 13
  • 220
  • 245
Sameer Sawla
  • 729
  • 6
  • 20
  • Thank you and for KmlFactory,createKml you can use something similar to this `// return kml.marshal(System.out) StringWriter sw = new StringWriter() kml.marshal(sw) return sw.toString()` – V H Nov 30 '17 at 15:19
0
  1. Generic solution

Create a NoEscapeHandler implementing CharacterEscapeHandler (look for example at com.sun.xml.bind.marshaller.DumbEscapeHandler

import java.io.IOException;
import java.io.Writer;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

public class NoEscapeHandler implements CharacterEscapeHandler {

    private NoEscapeHandler() {}  

    public static final CharacterEscapeHandler theInstance = new NoEscapeHandler(); 

    public void escape(char[] ch, int start, int length, boolean isAttVal, Writer out) throws IOException {
        int limit = start+length;
        for (int i = start; i < limit; i++) {
            out.write(ch[i]);
        }
    }
}

then set the property for the marshaller

marshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", NoEscapeHandler.theInstance);

Or use a DataWriter

StringWriter sw = new StringWriter();
DataWriter dw = new DataWriter(sw, "utf-8", NoEscapeHandler.theInstance);
  1. Solution when using XmlStreamWriter and jaxb framgments

    final XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory(); streamWriterFactory.setProperty("escapeCharacters", false);

From here

Community
  • 1
  • 1
ZiglioUK
  • 2,573
  • 4
  • 27
  • 32