我必须在两个列表的元素之间进行引用。我尝试过使用XStream。这是XML的例子:
<bookshop>
<authors>
<author id="a1">
<name>Stanisław</name>
</author>
</authors>
<books>
<book id="b1">
<author>a1</author>
<title>Ubik</title>
<price currency="PLN">29.0</price>
</book>
</books>
</bookshop>
以及我的Java类的一些划痕:
public class Bookshop {
private ArrayList<Author> authors;
private ArrayList<Book> boooks;
}
public class Book {
@XStreamAsAttribute
private String id;
private Author author;
private String title;
private Price price;
}
@XStreamConverter(value=ToAttributedValueConverter.class, strings={"value"})
public class Price {
private double value;
@XStreamAsAttribute
private String currency;
}
public class Author {
@XStreamAsAttribute
private String id;
private String name;
private String surname;
}
每次当我尝试将xml放入类中时,我会在Author autor字段中获取空值。也许我需要更多的注释,但我没有在Xstream文档中找到任何东西。
答案 0 :(得分:0)
您的XML
错了。如果您尝试序列化XStream
的实例,则Bookshop
给出了以下内容:
<bookshop>
<authors>
<author>
<id>a1</id>
<name>Yuri</name>
<surname>Stanislaw</surname>
</author>
<author>
<id>a2</id>
<name>Bill</name>
<surname>Gates</surname>
</author>
</authors>
<books>
<book>
<id>b1</id>
<author reference="/bookshop/authors/author[2]"/>
<title>Programming basics</title>
<price>
<currency>USD</currency>
<value>100.0</value>
</price>
</book>
</books>
</bookshop>
上面的XML
使用以下设置序列化:
xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
xstream.alias("bookshop", Bookshop.class);
xstream.alias("author", Author.class);
xstream.alias("book", Book.class);
我可以找到用于测试的完整源代码here
如果这不足以解决参考问题,我建议编写自己的Converter
以便与XStream一起使用,可以找到一个简短的教程here