[更新] 我正在尝试使用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();
然后我得到空
答案 0 :(得分:0)
代码需要稍作更改,以适应针对单个Country对象的交易列表。
包含交易清单的类:
@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);