I need to parse an XML file then map it to a Java object. So far, I do it with an annotated POJO :
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"title", "id", "eventList"})
@XmlRootElement(name = "MyClass")
public class MyClass {
@XmlElement(name = "Title", required = true)
protected String title;
@XmlElement(name = "Id", required = false)
protected String id;
@XmlElement(name = "EventList", required = true)
protected EventList eventList;
}
Then unmarshall it with JAXB :
MyClass myObj = (MyClass) unmarshaller.unmarshal(new StreamSource(fis))
Problem : Sometimes, my customer send files with slightly different tag names (for example, Eventlist
instead of EventList
)
Is there an option to allow both names for a tag? Up to now, I solve this problem by giving 2 attributes in the POJO :
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"title", "id", "eventList"})
@XmlRootElement(name = "MyClass")
public class MyClass {
@XmlElement(name = "Title", required = true)
protected String title;
@XmlElement(name = "Id", required = false)
protected String id;
@XmlElement(name = "EventList", required = false)
protected EventList eventList;
@XmlElement(name = "Eventlist", required = false)
protected EventList eventlist;
}
This is hard to maintain and forbids me to use the 'required' attribute. Do you have a better solution?
I am not sure there is an option to add multiple names, but what you can do is:
make the fields private and add getters and setters for them. You can make 2 getters and setters for the eventlist-field and annotate them with different names. Since this field is not required, as I see, there will be no problem.
Although.. as I see now, the problem is actually solved. See here: JAXB: unmarshalling xml with multiple names for the same element
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.