【发布时间】:2011-07-25 00:58:13
【问题描述】:
我认为我的 XStream 工作可能过于“放大”,但我正在尝试编组一个 XML 流,其中包含各种大型复杂对象,并且每个对象往往都有很多标签如:
<name type="string">My Name</name>
<speed type="dice">2d6</speed>
所以我创建了一个“TypedString”对象,用类型属性来包装字符串的概念,如下所示:
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
public class TypedString {
@XStreamAsAttribute
private String type;
private String value;
public TypedString(String type, String value) {
this.type = type;
this.value = value;
}
// getters omitted
}
现在,我知道这一定是遗漏了一些东西——我怎样才能使用标签的内容获取“值”变量集(例如,对于上面显示的第一个示例,类型将是“字符串”,值将是“我的名字”)。
我为此写了一个简短的单元测试:
public class TypedStringTest {
private XStream xStream;
@Before
public void setUp() {
xStream = new XStream();
xStream.processAnnotations(TypedString.class);
xStream.alias("name", TypedString.class);
}
@Test
public void testBasicUnmarshalling() {
TypedString typedString = (TypedString) xStream.fromXML("<name type=\"string\">Name</name>");
assertEquals("string", typedString.getType());
assertEquals("Name", typedString.getValue());
}
}
第二个断言失败。
是否需要向 TypedString 类添加注释才能使其正常工作?或者我真的在这里放大得太远了(例如,这一切都应该在包含这些标签的类中的注释上完成吗?)。 @XStreamAsAttribute 注释看起来不像可以从父标记中使用 - 据我所知,它需要在表示应用的标记的对象上定义。因此,我制作了一个美化的字符串,我觉得 XStream 应该在没有我隐式帮助的情况下进行编组。
简而言之,我在哪里迷路了?!
【问题讨论】:
-
环顾网站寻找答案后,我看到的最好的是转换器——真的没有办法在 XStream 中使用注释吗?
标签: annotations xstream