在解组XML时获取空值

时间:2017-08-28 21:06:16

标签: jaxb

任何人都可以帮我解决这个JAXB解组问题吗?

所以,这是我正在使用的文件employee.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<parent>
  <anotherchild1>Another</anotherchild1>
</parent>

这是具有JAXB注释的Parent.java类:

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package XMLToObject;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Gauravb
 */
@XmlRootElement 
public class Parent {
    private String child;
    private String anotherchild1;

    public String getAnotherChild1() {  
        return anotherchild1;  
    }  
    public void setAnotherChild1(String child) {  
        this.anotherchild1 = anotherchild1;  
    }




}

这是我正在使用的XMLToObject.java文件:

    package XMLToObject;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Gauravb
 */
import java.io.File;  
import javax.xml.bind.JAXBContext;  
import javax.xml.bind.JAXBException;  
import javax.xml.bind.Unmarshaller;  

public class XMLToObject {  
public static void main(String[] args) {  
     try {    
            File file = new File("employee.xml");    
            JAXBContext jaxbContext = JAXBContext.newInstance(Parent.class);    
         System.out.println("Reading....."+file.getAbsolutePath());  
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();    

            Parent p = (Parent) jaxbUnmarshaller.unmarshal(file);

            //System.out.println("Child:"+p.getChild());  
            System.out.println("Another Child:"+p.getAnotherChild1());  

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

}  
}  

现在,我的问题是当我运行XMLToObject.java文件时,我看到以下内容:

Reading.....C:\xxxxxx\employee.xml
Another Child:null

那么,任何人都可以告诉我这个价值背后的原因是什么?

请注意: 我是JAXB的新手 2.我在运行代码时使用Netbeans编辑器 3.我没有XML的XSD,也不想使用任何我的学习 4.我现在不想使用MOXy,这是我接下来要学习的东西

1 个答案:

答案 0 :(得分:0)

您忘记在绑定类Parent.java中添加@XmlElement批注,如下所示

    @XmlElement
    private String anotherchild1;
相关问题