使用xstream将XMLl转换为Java对象

时间:2015-10-12 18:39:58

标签: xml xstream

我有以下xml。如何使用xstream转换为java对象。我尝试了几种方法,但最终我得到了转换。 代码如下。我不知道如何转换为BookDetails对象。

XML字符串:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Books>
    <bookdetails>
    <bookId>20</bookId>
    <bookName>AAAA</bookName>
    <amount>35</amount>
    </bookdetails>
    </Books>

BookDetails类:

@XStreamAlias("bookDetails")
public class BookDetails {
@XStreamAlias("bookId")
private int bookId;
@XStreamAlias("bookName")
private String bookName;
@XStreamAlias("amount")
private int amount;
//getters and setters
}

图书类:

@XStreamAlias("Books")
public class Books{

@XStreamAlias("bookDetails")
private List<BookDetails> bookDetails=new ArrayList<BookDetails>();
}

--------------unmarshall class method----

public BookDetails convertXml(String xml){

            xstream.processAnnotations(Books.class);
            xstream.processAnnotations(BookDetails.class);
            xstream.addImplicitCollection(Books.class,"BookDetails");
            return (BookDetails)xstream.fromXML(processOrderXML);
}

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

首先,您对BookDetails类使用了错误的别名。您将其声明为@XStreamAlias("bookDetails"),并且您的XML标记全部为小写bookdetails

然后您使用错误的字段名称来定义隐式集合:它应该是bookDetails - 作为列表字段名称,而不是BookDetails

最后,您必须解析完整的XML,然后才能从中获取BookDetails数据。而不是创建BookDetails实例XStream将为您提供Books实例。

作为补充观察,您不必为具有确切名称作为XML标记的字段添加别名。

更正后的代码为:

@XStreamAlias("bookdetails")
public class BookDetails
{
    private int bookId;
    private String bookName;
    private int amount;
}

@XStreamAlias("Books")
public class Books
{
    private List<BookDetails> bookDetails = new ArrayList<BookDetails>();
}

public BookDetails convertXml(String xml)
{
    xstream.processAnnotations(Books.class);
    xstream.processAnnotations(BookDetails.class);
    xstream.addImplicitCollection(Books.class, "bookDetails");
    Books b = (Books) xstream.fromXML(xml);
    // and now you can return your BookDetails element (in case you want only first one)
    return b.bookDetails.get(0);
}