如何在单个顶级对象Java中封装复杂的xml数据

时间:2017-04-04 05:17:18

标签: java xml jaxb

我会尽力清楚。这个问题的灵感来自多年前的一个问题。

我想将xml数据封装到一个Root元素对象中。

所以对于以下 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FosterHome>
    <Orphanage>Happy Days Daycare</Orphanage>
    <Location>Apple Street</Location>
    <Families>
        <Family>
            <ParentID>Adams</ParentID>
            <ChildList>
                <ChildID>Child1</ChildID>
                <ChildID>Child2</ChildID>
            </ChildList>
        </Family>
        <Family>
            <ParentID>Adams</ParentID>
            <ChildList>
                <ChildID>Child3</ChildID>
                <ChildID>Child4</ChildID>
            </ChildList>
        </Family>
    </Families>
    <RemainingChildList>
        <ChildID>Child5</ChildID>
        <ChildID>Child6</ChildID>
    </RemainingChildList>
</FosterHome>

我有以下JAXB注释类。

FosterHome.java

import java.util.List;
import javax.xml.bind.annotation.*;

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

    @XmlElement(name="Orphanage")
    private String orphanage;

    @XmlElement(name="Location")
    private String location;

    @XmlElementWrapper(name="Families")
    @XmlElement(name="Family")
    private List<Family> families;

    @XmlElementWrapper(name="RemainingChildList")
    @XmlElement(name="ChildID")
    private List<String> remainingChildren;
}

Family.java

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Family {

    @XmlElement(name="ParentID")
    private String parentID;

    @XmlElementWrapper(name="ChildList")
    @XmlElement(name="ChildID")
    private List<String> childList;
}

Demo.java

public static FosterHome parseXML(File file) {
    try {
        JAXBContext context = JAXBContext.newInstance(FosterHome.class);
        Unmarshaller um = context.createUnmarshaller();

        FosterHome fosterHome = (FosterHome) um.unmarshal(file);

        for(Family family : fosterHome.getFamilies()) {
            for(String childID : family.getChildList()) {
                System.out.println(childID);
                // my question is here
                // How to encapsulate all the data into the fosterHome object
                // such as:
                // FosterHome fh = childID.getChildID(); 
            }
        }
        return fosterHome;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


public static void main(String[] args) {
    FosterHome fh = parseXML(new File("./testdata/jaxbtest.xml"));
    sysout(fh); // print out all the data from the xml example from above including the data for ChildID
}

所以我的问题是: 如何获取类型为FosterHome的ChildID,看起来ChildID属于Family类型,因此如果您希望fosterHome对象包含childID,则可能无效。有谁知道这样做的方法?像FosterHome.Family这样的东西可能是不可能的,因为这些类是分离的。因此,当我执行fosterHome.getChildID()时,我将获得类型为FosterHome的childID。

0 个答案:

没有答案