0

我必须在两个列表的元素之间进行引用。我尝试过使用 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 文档中没有找到任何内容。

4

1 回答 1

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

我用于测试的完整源代码可以在这里找到

如果这不是参考问题的充分解决方案,我建议您自己编写Converter以与 XStream 一起使用,可以在此处找到简短教程

于 2013-01-09T22:36:14.320 回答