XStream and underscores

我是研究僧i 提交于 2019-12-03 07:48:06

问题


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;
}

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?


回答1:


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.




回答2:


This worked for me:

XStream xs = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("_-", "_")));



回答3:


I used:

XmlFriendlyNameCoder nameCoder = new XmlFriendlyNameCoder("ddd", "_");  
XStream xmlStream = new XStream(new Dom4JDriver(nameCoder)); 

and it worked great! I am using x-stream version 1.4.5. Hope it helps!




回答4:


Worked for me:

XStream xstream = new XStream(new DomDriver("UTF_8", new NoNameCoder()));


来源:https://stackoverflow.com/questions/9333035/xstream-and-underscores

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!