eigil eigil - 11 months ago 61
Java Question

XStream and underscores

It looks like XStream (com.thoughtworks.xstream -> xstream 1.4.2) is handling underscores in element and attribute names in a very strange way. I need to fetch and parse an xml from a customer that are having underscores in their attributes. This is my first try with XStream and I'm a bit disappointed as I was hoping to avoid all the ugly xml parsing.

Here I provide a small test sample to hi light the behaviour. The last example shows my problem.

public class MyTest {
public void testIt() {
C1 a = new C1();
a.a_b= "a_b";

XStream xstream = new XStream();

String xml = xstream.toXML(a);

C1 b = (C1) xstream.fromXML(xml);

C1 c = (C1) xstream.fromXML("<C1 a_b=\"a_b\"/>");

class C1 {
String a_b;

This outputs

INFO: <C1 a__b="a_b"/>
INFO: a_b
INFO: null

Now my question - is there a way to make XStream understand a single underscore?

Answer Source

XStream uses the underscore to escape characters in identifiers that are valid in Java but invalid in XML (see here). So the underscore itself has to be escaped. You can use a custom NameCoder as described in the FAQ.

That said I normally can get along with the NoNameCoder. But: Don't use underscores in Java property identifiers, if possible; it is untypical for Java and against the Java Naming Conventions.