java xml 下划线,XStream和下划线

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();

xstream.processAnnotations(C1.class);

String xml = xstream.toXML(a);

Logger.info(xml);

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

Logger.info(b.a_b);

C1 c = (C1) xstream.fromXML("");

Logger.info(c.a_b);

}

}

@XStreamAlias("C1")

class C1 {

@XStreamAsAttribute

String a_b;

}

This outputs

INFO:

INFO: a_b

INFO: null

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值