基于名称标记和必需标记的解组(XML,JAXB,Java)

时间:2017-07-10 21:22:28

标签: xml jaxb unmarshalling

所以我有以下测试xml文件,该文件已经解组正确

<group>
    <field><testName>n</testName></field>
    <field><testName>n</testName></field>
    <field><testName>n</testName></field>
    <group>
        <field><testName>n</testName></field>
        <field><testName>n</testName></field>
    </group>
</group>

但我想将功能扩展为:

<group name="gname" required="N">
    <field name="fname" required="N"/>
    <field name="fname1" required="N"/>
    <field name="fname2" required="N"/>
    <group name="gname1" required="N">
        <field name="fname3" required="N"/>
        <field name="fname4" required="N"/>
    </group>
</group>

如何解组并将名称必需字段存储到字段对象中?最好是每个和/或字段对象中的键值对。

小组课程

@XmlRootElement(name = "group")
@XmlAccessorType(XmlAccessType.FIELD)
public class Group {
    @XmlElement (name = "field")
    private List<Field> fields = null;
    @XmlElement(name = "group")
    private List<Group> groups = null;

    /**
    *possibly include
    *String name = null;
    *String required = null;
    **/

    public List<Group> getGroups() {
        return this.groups;
    }

    public void setEmployees(List<Group> groups) {
        this.groups = groups;
    }

    public List<Field> getFields() {
        return fields;
    }

    public void setFields(List<Field> fields) {
        this.fields = fields;
    }
}

Field Class

@XmlRootElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
public class Field {
    private String testName = null;

    /**
    *possibly include
    *String name = null;
    *String required = null;
    **/

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

static void unMarshallingTest() throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Group.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    Group groups = (Group) unmarshaller.unmarshal(new File(
            "C:\\Users\\u589329\\IdeaProjects\\ConfigFiles\\src\\innerTest.xml"));

    for (Field f: groups.getFields()) {
        System.out.println(f.getName());
        System.out.println("here");
    }

    for (Group g: groups.getGroups()) {
        for (Field f: groups.getFields()) {
            System.out.println(f.getName());
            System.out.println("or here");
        }
    }
}

public static void main(String[] args) {
    try {
        unMarshallingTest();
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

为您的班级@XmlAttributeGroup添加带有Field注释的字段:

@XmlAttribute
private String name;

@XmlAttribute
private String required;