繁体   English   中英

使用JAXB解组xml文件

[英]unmarshal an xml file using JAXB

[更新]我正在尝试使用jaxb将xml元素存储到arraylist中。 我看过很多关于将以下xml格式存储到对象或arraylist中的教程

<country>
   <name>nepal</name>
   <zip>123</zip>
</country>

我尝试了如下所示的不同类型的xml文件,但没有解决

<TransactionList>
<Transaction type="D" amount="61" narration="Electricity bill" />
<Transaction type="D" amount="32" narration="Social security payment" />
<Transaction type="D" amount="33" narration="Payment sent to x" />
<Transaction type="C" amount="111" narration="Salary" />
<Transaction type="D" amount="233" narration="Car rental" />

我试过下面的代码

try {

                File file = new File("C:\\Users\\anon\\Desktop\\Transaction_Data.xml");
                JAXBContext jaxbContext = JAXBContext.newInstance(Transaction.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Transaction transaction = (Transaction) jaxbUnmarshaller.unmarshal(file);
                System.out.println(transaction);


              } catch (JAXBException e) {
                e.printStackTrace();
              }

我的pojo类(Transaction.java)

@XmlRootElement(name="TransactionList")
@XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {

@XmlElement(name="type")
private String type;

@XmlElement(name="amount")
private BigDecimal amount;

@XmlElement(name="narration")
private String narration;

@XmlElement(name = "Transaction")
private List<Transaction> transaction= null;

public List<Transaction> getTransaction() {
    return transaction;
}

public void setTransaction(List<Transaction> transaction) {
    this.transaction = transaction;
}

我现在得到这个作为输出

com.progressoft.induction.tp.models.Transaction@0

当我尝试这样做时

transaction.getAmount(); 

然后我得到空

代码需要进行一些细微的更改,以适应针对单个Country对象的Transaction列表。

包含交易清单的类别:

@XmlRootElement(name = "transactions")
@XmlAccessorType (XmlAccessType.FIELD)
public class Transactions
{
    @XmlElement(name = "transactions")
    private List<Transaction> transactions= null;

    public List<Transaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<Transaction> transactions) {
        this.transactions= transactions;
    }
}

交易类别:

@XmlRootElement(name = "employee")
@XmlAccessorType (XmlAccessType.FIELD)
public class Transaction 
{
    private Integer type;
   .......

商业逻辑:

Transactions transactions = (Transactions) jaxbUnmarshaller.unmarshal(file);
                System.out.println(transaction);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM