JAXB 2.x: Marshalling met valeur de l'élément deux fois dans le XML
-
25-10-2019 - |
Question
Pour une raison quelconque, toutes les valeurs d'un élément s'écrit deux fois. Mon cas de test est très simple:
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class TestBean {
private String name = null;
@XmlElement(name="lastname")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Alors je marshall le document au système de fichiers dans un fichier XML:
TestBean object = new TestBean();
object.setName("abc ");
Class<?> clazz = object.getClass();
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.marshal(object, new File("test.xml"));
Et le XML résultant est:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<lastname>abc abc </lastname>
</root>
Pour simplifier, je supprimé le fichier package-info.java avec les définitions d'espace de noms.
La mise en œuvre que je utilise est org.eclipse.persistence.moxy 2.1.2: le fichier jaxb.properties dans le dossier de package contient cette ligne:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Merci pour tout conseils.
La solution
This is a known MOXy issue that has been fixed in the EclipseLink 2.3.0 stream. An EclipseLink 2.3.0 download can be obtained here:
The workaround for EclipseLink 2.1.2 is to use another access type, or to annotate the corresponding field with @XmlTransient:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="root")
public class TestBean {
@XmlTransient
private String name = null;
@XmlElement(name="lastname")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Autres conseils
I tried your test and it gives the correct output for me:
<root>
<lastname>abc </lastname>
</root>
It could be the JAXB2 implementation (moxy in your case vs native JDK1.6 based JAXB2 for my test).