我必须查询返回包含一张发票或发票列表的 XML 文件的多个 URL(我知道哪些 URL 将返回一个列表,哪些将只返回一个发票)。
单张发票格式(简体):
<?xml version="1.0" encoding="UTF-8"?>
<invoice>
<invoice-id>1</invoice-id>
</invoice>
发票清单的格式:
<?xml version="1.0" encoding="UTF-8"?>
<invoices>
<invoice>
<invoice-id>1</invoice-id>
</invoice>
<invoice>
<invoice-id>2</invoice-id>
</invoice>
</invoices>
Jersey 可以自动处理第一个 xml 片段并将其转换为 Java 类:
@XmlRootElement
public class Invoice {
@XmlElement(name="invoice-id")
Integer invoiceId;
}
这是通过以下代码完成的:
GenericType<JAXBElement<Invoice>> invoiceType = new GenericType<JAXBElement<Invoice>>() {};
Invoice invoice = (Invoice) resource.path("invoice_simple.xml").accept(MediaType.APPLICATION_XML_TYPE).get(invoiceType).getValue();
以上作品。
现在我想要一个 InvoiceList 对象,如下所示:
@XmlRootElement
public class InvoiceList {
@XmlElementWrapper(name="invoices")
@XmlElement(name="invoice")
List<Invoice> invoices;
}
这是我遇到问题的地方;InvoiceList.invoices 在以下情况下保持为空:
GenericType<JAXBElement<InvoiceList>> invoicesType = new GenericType<JAXBElement<InvoiceList>>() {};
InvoiceList invoices = (InvoiceList) resource.path("invoices_simple.xml").accept(MediaType.APPLICATION_XML_TYPE).get(invoicesType).getValue();
// now invoices.invoices is still null!
我知道 Jersey/JAXB 可以处理对象列表,但如果顶部元素包含列表,它似乎将不起作用。
所以,我的问题是:如何指示 Jersey 解析包含发票对象列表的 xml 文件?