在XML文件中解组一对一关系

时间:2014-05-01 15:51:04

标签: java xml jaxb marshalling unmarshalling

当我尝试将 Person.xml 解组为 POJO 并将其打印出来时,父对象打印出正常但 ChildThree.java 打印出null

Test.java

public class Test {

    public static void main(String[] args) {
        try {
            File file = new File("src/xml/person.xml");
            System.out.println(file.getAbsolutePath());
            JAXBContext jaxbContext = JAXBContext.newInstance(Parent.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Parent parent = (Parent) jaxbUnmarshaller.unmarshal(file);
            System.out.println(parent);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Person.xml

<?xml version="1.0" encoding="utf-8"?>
<Parent>
    <ChildOne>1</Child>
    <ChildTwo>2</Child>
    <ChildThree>
        <Name>3</Name>
        <Age>Ten</Age>
    </ChildThree>
</Parent>

Parent.java

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

    @XmlElement
    private String ChildOne;
    @XmlElement
    private String ChildTwo;
    @XmlElement
    private ChildThree ChildThree;

    public String getChildOne() {
        return ChildOne;
    }

    public void setChildOne() {
        this.ChildOne = ChildOne;
    }

    public String getChildTwo() {
        return ChildTwo;
    }

    public void setChildTwo() {
        this.ChildTwo = ChildTwo;
    }


    public ChildThree getChildThree() {
        return ChildThree;
    }

    public void setChildThree() {
        this.ChildThree = ChildThree;
    }

}

ChildThree.java

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

    @XmlElement
    private String Name;
    @XmlElement
    private String Age;

    public String getName() {
        return Name;
    }

    public void setName() {
        this.Name = Name;
    }

    public String getAge() {
        return Age;
    }

    public void setAge() {
        this.Age = Age;
    }
}

2 个答案:

答案 0 :(得分:1)

以下内容应该有所帮助:

  1. 在课堂上指定@XmlAccessorType(XmlAccessType.FIELD)时,应将注释放在字段(实例变量)而不是属性(get / set方法)上,(参见:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html)。
  2. 确保您的get / set方法遵循相应的bean约定:
    • String getFoo()
    • void setFoo(String)
  3. 认识到JAXB具有将Java中的字段/属性名称转换为可能与您的期望不同的XML名称的规则。当您有解组问题时,填充对象模型并编组它以查看JAXB期望的内容通常很有用(请参阅:http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html)。

答案 1 :(得分:0)

通过替换:

来修复它
@XmlElement
private ChildThree ChildThree;

使用:

@XmlElement(name = "ChildThree")
private List<ChildThree> childThree;