I wanted to serialize a java class to XML with XStream.
I needed to generated an XML element with one underline (canal_operateur), but XStream adds a second underline in the xml element name.
So how to keep only one underline ?
With the default configuration for this class :
public class Document implements Serializable {
private String typedoc;
private Fichier fichier;
private String canalOperateur;
//xstream.aliasField("canal_operateur", Document.class, "canalOperateur");
/*
** setter and getter
*/
}
XStream doubles the underline :
<document>
<canal__operateur>canal</canal__operateur>
<commentaire>commentaire</commentaire>
<metadonnees/>
</document>
According to here:
XStream maps Java class names and field names to XML tags or attributes. Unfortunately this mapping cannot be 1:1, since some characters used for identifiers in Java are invalid in XML names. Therefore XStream uses an XmlFriendlyNameCoder to replace these characters with a replacement. By default this NameCoder uses an underscore as escape character and has therefore to escape the underscore itself also. You may provide a different configured instance of the XmlFriendlyNameCoder or a complete different implementation like the NoNameCoder to prevent name coding at all. However it is your responsibility then to ensure, that the resulting names are valid for XML.