所以我有以下测试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;
}
}
@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();
}
}
答案 0 :(得分:0)
为您的班级@XmlAttribute
和Group
添加带有Field
注释的字段:
@XmlAttribute
private String name;
@XmlAttribute
private String required;