Java 解析顶部元素包含对象列表的XML文档
我必须查询多个URL,这些URL返回包含一张发票或发票列表的XML文件(我知道哪些URL将返回列表,哪些URL将只返回一张发票) 单一发票的格式(简化): 这是通过以下代码完成的:Java 解析顶部元素包含对象列表的XML文档,java,xml,jaxb,jersey,Java,Xml,Jaxb,Jersey,我必须查询多个URL,这些URL返回包含一张发票或发票列表的XML文件(我知道哪些URL将返回列表,哪些URL将只返回一张发票) 单一发票的格式(简化): 这是通过以下代码完成的: GenericType<JAXBElement<Invoice>> invoiceType = new GenericType<JAXBElement<Invoice>>() {}; Invoice invoice = (Invoice) resource.path("
GenericType<JAXBElement<Invoice>> invoiceType = new GenericType<JAXBElement<Invoice>>() {};
Invoice invoice = (Invoice) resource.path("invoice_simple.xml").accept(MediaType.APPLICATION_XML_TYPE).get(invoiceType).getValue();
GenericType invoiceType=新的GenericType(){};
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;
}
@XmlRootElement
公共类发票列表{
@XmlElementWrapper(name=“发票”)
@xmlement(name=“发票”)
列出发票;
}
这就是我遇到问题的地方;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!
GenericType invoicesType=new-GenericType(){};
发票列表发票=(发票列表)资源.path(“发票”\u simple.xml”).accept(MediaType.APPLICATION\u xml\u TYPE).get(发票类型).getValue();
//现在invoices.invoices仍然为空!
我知道Jersey/JAXB可以处理对象列表,但如果顶层元素包含该列表,则它似乎无法工作
所以,我的问题是:如何指示Jersey解析由发票对象列表组成的xml文件
将nillable=true
放在@xmlement
上
@xmlement(name=“invoice”,nillable=true)
列出发票;
我很喜欢这个。(不必包装已包装的集合。)
@XmlRootElement
公共类发票{
公共列表getInvoices(){
如果(发票==null){
发票=新的ArrayList();
}
退回发票;
}
@XmlElement(name=“invoice”,nillable=true)
私人清单发票;
}
一些JAX-RS示例如下所示
@GET
@路径(“/invoices”)
公共发票{
// ...
}
@得到
@路径(“/invoices/{invoices\u id:\\d+}”)
公共发票readInvoice(@PathParam(“发票id”)最终长发票id){
// ...
}
GenericType<JAXBElement<Invoice>> invoiceType = new GenericType<JAXBElement<Invoice>>() {};
Invoice invoice = (Invoice) resource.path("invoice_simple.xml").accept(MediaType.APPLICATION_XML_TYPE).get(invoiceType).getValue();
@XmlRootElement
public class InvoiceList {
@XmlElementWrapper(name="invoices")
@XmlElement(name="invoice")
List<Invoice> 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!