有人可以给我以下情况的建议吗: 我的 xml 文件中有这样的结构:
<?xml ... ?>
<root>
<listof_aaa>
<aaa>aaa_object</aaa>
<aaa>aaa_object</aaa>
...
</listof_aaa>
<listof_bbb>
<bbb>bbb_object</bbb>
<bbb>bbb_object</bbb>
...
</listof_bbb>
<listof_ccc>
<ccc>ccc_object</ccc>
<ccc>ccc_object</ccc>
...
</listof_ccc>
</root>
我的目标是首先读取所有 aaa-objects,然后是 bbb 等等...... 如果在根标记中我有几个不同的对象系列,我该如何解析这样的结构?我考虑过使用 JAXB,但无法理解,在这种情况下我能如何使用它。
附注所有对象族都是 POJO。 谢谢!
最佳答案
您的情况下典型的自动生成的类如下所示:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"listof_aaa",
"listof_bbb",
"listof_ccc",
"listinside"
})
@XmlRootElement(name = "root")
public class Root {
@XmlElement(required = true)
protected Listof_aaa listof_aaa;
protected Listof_bbb listof_bbb;
protected Listof_ccc listof_ccc;
protected java.util.List<Listinside> listinside // example of multiple elements with one node name under the root
public Listof_aaa getListof_aaa() {
return listof_aaa;
}
public void setListof_aaa(Listof_aaa value) {
this.listof_aaa = value;
}
// other getters and setters
// and an example of multiple elements under the root
public java.util.List<Listinside> getListinside() {
if (listinside == null) {
listinside = new ArrayList<Listinside>();
}
return this.sec;
}
}
迭代:
public static void main(String[] args) throws JAXBException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
Unmarshaller unmarhsaller = jaxbContext.createUnmarshaller();
Root root = (Root) unmarhsaller.unmarshal(new File("pathToYourFile.xml"));
Listof_aaa listof_aa = root.getListof_aaa();
/* and in case of a list */
List<Listinside> listinside = root.getListinside();
for (List myList : listinside) {
// do your stuff
}
}
关于java - 我如何处理使用 Jaxb 解析的 xml 文件而不是从根元素解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832971/