无法编组嵌套的xml元素

时间:2014-04-26 20:44:39

标签: java xml jaxb nested

我尝试使用嵌套元素从java类创建XML。 我不知道我的错误在哪里,我应该改变什么 谢谢!

我的主要课程:

String MY_XML = "my path...";  //hier is the path...

JAXBContext context = JAXBContext.newInstance(MasterDataRM.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

 Master temp = new Master();
 temp.setTransactionStatus("AlmostOk");
 m.marshal(temp, new File(MY_XML));
 m.marshal(temp, System.out);

我要上课的课程:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Master {

    @XmlElement
    protected Date ResponseDatetime = new Date();

    @XmlElement
    protected Transaction transaction;


    public void setResponseDatetime(Date date){
        this.ResponseDatetime = date;
    }

    public Date getDate(){
        return ResponseDatetime;
    }

    public static class Transaction{
        @XmlElement
        String status = "OK";
    }

    public void setStatus(String status){ 
        transaction.status = status; //  This throws the NullPointerException !!!
    }

    public String getStatus(){
        return transaction.status;
    }

1 个答案:

答案 0 :(得分:0)

transaction.status = status; // This throws the NullPointerException !!!

因为你没有初始化内部静态类,所以请记住在用户之前初始化实例变量的所有方法,这就是为什么你得到 NLP

首先创建Transcation对象,然后使用外部类对象将其设置为

temp.setTransaction(new Master.Transaction());

一样更新你的课程
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Master {

    public Master() {
    }

    @XmlElement
    protected Date ResponseDatetime = new Date();

    @XmlElement
    protected Transaction transaction;

    public void setResponseDatetime(Date date) {
        this.ResponseDatetime = date;
    }

    public Date getDate() {
        return ResponseDatetime;
    }

    public static class Transaction {
        @XmlElement
        String status = "OK";
    }

    public void setStatus(String status) {
        transaction.status = status; // This throws the NullPointerException !!!
    }

    public String getStatus() {
        return transaction.status;
    }

    public Transaction getTransaction() {
        return transaction;
    }

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

}

沼泽吧

JAXBContext jaxbContext = JAXBContext.newInstance(Master.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Master temp = new Master();
        temp.setTransaction(new Master.Transaction());
        temp.setStatus("AlmostOk");
        jaxbMarshaller.marshal(temp, new File(MY_XML));
        jaxbMarshaller.marshal(temp, System.out);