XStream和下划线 [英] XStream and underscores

查看:548
本文介绍了XStream和下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来XStream(com.thoughtworks.xstream - > xstream 1.4.2)以非常奇怪的方式处理元素和属性名称中的下划线。我需要从客户中获取并解析xml,这些客户的属性中包含下划线。这是我第一次尝试使用XStream,我有点失望,因为我希望避免所有丑陋的xml解析。

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("<C1 a_b=\"a_b\"/>");
    Logger.info(c.a_b);
  }
}

@XStreamAlias("C1")
class C1 {
@XStreamAsAttribute
String a_b;
}

此输出

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

现在我的问题 - 是否有让XStream理解单个下划线的方法?

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

推荐答案

XStream使用下划线来转义在Java中有效但无效的标识符中的字符XML格式(请参阅此处)。所以下划线本身必须被转义。您可以使用常见问题解答中描述的自定义 NameCoder

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.

这说我通常可以与 NoNameCoder 。但是:如果可能,不要在Java属性标识符中使用下划线;它不适用于Java和 Java命名约定

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.

这篇关于XStream和下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆