0
votes

When attempting to marshall a string containing valid XML as an @XmlValue property of another object, the string is incorrectly encoded.

For the source string:

<person><nickname>Jughead</nickname></person>

The marshaller returns:

&lt;person>&lt;nickname>Jughead&lt;/nickname>&lt;/person>

(Note that < is correctly escaped as &lt; but > is not escaped.)

This problem seems to be implementation dependent as the same code works as expected (returning &lt;person&gt; etc) with the default Java 8 JAXB implementation.

Sample code:

package au.com.schreuder.moxy.test;

import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;

public class Main {

    @XmlRootElement(name = "model")
    @XmlAccessorType(XmlAccessType.NONE)
    public static class Model {

        private String value;

        @XmlValue
        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    } 

    public static void main(String[] args) throws Exception {
        System.out.println("moxy.test.main");

        Model model = new Model();
        model.setValue("<person><nickname>Jughead</nickname></person>");

        System.out.println(marshallFragment(model));
    }

    public static String marshallFragment(Object o)
            throws Exception {

        JAXBContext context = JAXBContext.newInstance(o.getClass());
        System.out.println(context.getClass());
        Marshaller m = context.createMarshaller();
        System.out.println(m.getClass());

        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        StringWriter writer = new StringWriter();
        m.marshal(o, writer);

        return writer.toString();
    }
}

And the complete dependencies from pom.xml:

<dependencies>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.moxy</artifactId>
        <version>2.6.5</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

I hope someone can help!

1

1 Answers

0
votes

XML does not require > to be escaped unless it appears as part of the sequence ]]>. So both serializations are perfectly acceptable.