2014-04-26 67 views
0

Im嘗試使用嵌套元素從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; 
    } 

回答

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);