0
如何在JAXB的幫助下處理這樣的結構? 有一個父根目錄和許多其他的內容,它們保存有關許多對象(例如狀態)的信息。如何在JAXB的幫助下處理嵌套的xml標記?
<?xml version='1.0' encoding='utf-8'?>
<root>
<states>
<state>
<name>Alabama</name>
<id>al</id>
</state>
<state>
<name>Alaska</name>
<id>ak</id>
</state>
...
</states>
<airports>
<airport>
...
</airport>
<airport>
...
</airport>
...
</airports>
...
</root>
如果狀態,我創建的類國家:
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class States {
@XmlElement(name="states")
private List<State> states;
public List<State> getBrokers(){
return states;
}
public void setBrokers(List<State> states) {
this.states = states;
}
}
和類國家:
@XmlAccessorType(XmlAccessType.FIELD)
public class State {
@XmlElement(name = "name")
private String name;
@XmlElement(name = "id")
private String id;
public State(){}
public State(String id, String name) {
this.id = id;
this.name = name;
}
但當我致電國對象
public class JaxbParser {
public Object getObject(File file, Class c) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
Object object = unmarshaller.unmarshal(file);
return object;
}
public void saveObject(File file, Object o) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(o.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(o,file);
}
}
public static void main(String[] args) throws JAXBException {
JaxbParser parser = new JaxbParser();
States brol = (States) parser.getObject(new File("C:\\Users\\...\\1.xml"), States.class);
List<State> brokerList = brol.getStates();
System.out.println(brol);
}
的stateList只包含一個id和id的狀態name等於null。 我在做什麼錯?
您將需要定義一個自定義的Xml適配器。 –
你在哪裏遍歷'List brokerList'? –
Vitaliy