在java中通过xstream从object生成xml

时间:2015-05-20 15:05:38

标签: java xml xstream

我正在使用xstream进行解析,将对象转换为xml我有以下pojo以及setter和getter

public class InvoiceReferenceNotificationMessage  {

    private String InvoiceReference;
    private String ABSReference;
    private String Currency;
    private double InvoiceAmount;
    private double PaidAmount;
    private double BalanceAmount;
    private Date ValueDate;
    private String Remarks;

    }

及以下我使用xstream以这种方式生成xml

public class InvoiceReferenceNotificationMessagetest {

        InvoiceReferenceNotificationMessage invoiceReferenceNotificationMessage = new InvoiceReferenceNotificationMessage();
        invoiceReferenceNotificationMessage.setInvoiceReference("SM/8315");
        invoiceReferenceNotificationMessage.setABSReference("IRMAR157311");
        invoiceReferenceNotificationMessage.setCurrency("GBP");
        invoiceReferenceNotificationMessage.setInvoiceAmount(2546);
        invoiceReferenceNotificationMessage.setPaidAmount(1245);
        invoiceReferenceNotificationMessage.setBalanceAmount(0);
        invoiceReferenceNotificationMessage.setValueDate(new Date());
        invoiceReferenceNotificationMessage.setRemarks("abc");

        XStream xstream = new XStream();
        xstream.alias("invoiceReferenceNotificationMessage",InvoiceReferenceNotificationMessage.class);
        String abc = xstream.toXML(invoiceReferenceNotificationMessage);

以及以下方式生成的xml是..

<invoiceReferenceNotificationMessage>
  <InvoiceReference>SM/8315</InvoiceReference>
  <ABSReference>IRMAR157311</ABSReference>
  <Currency>GBP</Currency>
  <InvoiceAmount>2546</InvoiceAmount>
  <PaidAmount>1245</PaidAmount>
  <BalanceAmount>0</BalanceAmount>
  <ValueDate>2015-05-20 19:57:51.188 IST</ValueDate>
  <Remarks>abc</Remarks>
</invoiceReferenceNotificationMessage>

现在我的查询是我想以下面的方式生成xml,如下所示,你可以看到下面的邮件标签是父标签 并且在其中有一个名为invoiceReferenceNotificationMessage的子标签,其中包含有关一个块的所有信息,请您告知如何实现相同的

<mail>

<invoiceReferenceNotificationMessage>
  <InvoiceReference>SM/8315</InvoiceReference>
  <ABSReference>IR311</ABSReference>
  <Currency>GBP</Currency>
  <InvoiceAmount>2546.0</InvoiceAmount>
  <PaidAmount>1245.0</PaidAmount>
  <BalanceAmount>0.0</BalanceAmount>
  <ValueDate>2015-05-20 19:57:51.188 IST</ValueDate>
  <Remarks>abc</Remarks>
  </invoiceReferenceNotificationMessage>


</mail>

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用包装类:

public class Mail
{
    private final InvoiceReferenceNotificationMessage invoiceReferenceNotificationMessage;
    public Mail(@Nonnull final InvoiceReferenceNotificationMessage msg)
    { this.invoiceReferenceNotificationMessage = msg; }
    public InvoiceReferenceNotificationMessage getinvoiceReferenceNotificationMessage() { return this.invoiceReferenceNotificationMessage; }
}

并将其序列化为您的根。