Saya memiliki masalah yang sama .. Ini membantu saya, saya menentukan nama bidang yang sama dari kelas saya sebagai nama tag di file xml (file tersebut berasal dari sistem eksternal).
Sebagai contoh:
File xml saya:
<Response>
<ESList>
<Item>
<ID>1</ID>
<Name>Some name 1</Name>
<Code>Some code</Code>
<Url>Some Url</Url>
<RegionList>
<Item>
<ID>2</ID>
<Name>Some name 2</Name>
</Item>
</RegionList>
</Item>
</ESList>
</Response>
Kelas Respon Saya:
@XmlRootElement(name="Response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {
@XmlElement
private ESList[] ESList = new ESList[1]; // as the tag name in the xml file..
// getter and setter here
}
Kelas ESList saya:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ESList")
public class ESList {
@XmlElement
private Item[] Item = new Item[1]; // as the tag name in the xml file..
// getters and setters here
}
Kelas Item saya:
@XmlRootElement(name="Item")
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
@XmlElement
private String ID; // as the tag name in the xml file..
@XmlElement
private String Name; // and so on...
@XmlElement
private String Code;
@XmlElement
private String Url;
@XmlElement
private RegionList[] RegionList = new RegionList[1];
// getters and setters here
}
Kelas RegionList saya:
@XmlRootElement(name="RegionList")
@XmlAccessorType(XmlAccessType.FIELD)
public class RegionList {
Item[] Item = new Item[1];
// getters and setters here
}
Kelas DemoUnmarshalling saya:
public class DemoUnmarshalling {
public static void main(String[] args) {
try {
File file = new File("...");
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
jaxbUnmarshaller.setEventHandler(
new ValidationEventHandler() {
public boolean handleEvent(ValidationEvent event ) {
throw new RuntimeException(event.getMessage(),
event.getLinkedException());
}
}
);
Response response = (Response) jaxbUnmarshaller.unmarshal(file);
ESList[] esList = response.getESList();
Item[] item = esList[0].getItem();
RegionList[] regionLists = item[0].getRegionList();
Item[] regionListItem = regionLists[0].getItem();
System.out.println(item[0].getID());
System.out.println(item[0].getName());
System.out.println(item[0].getCode());
System.out.println(item[0].getUrl());
System.out.println(regionListItem[0].getID());
System.out.println(regionListItem[0].getName());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Memberikan:
1
Some name 1
Some code
Some Url
2
Some name 2
ObjectFactory
dari sumber yang dihasilkan, yang lebih mungkin terjadi jika Anda mencampur dua direktori sumber yang dihasilkan berbeda.