[英]Unmarshal XML with dynamic root element using JAXB
I'm trying to integrate with a third-party system and depending on the type of object, the root element of the returned XML document changes.我正在尝试与第三方系统集成,并且根据对象的类型,返回的 XML 文档的根元素会发生变化。 For example:
例如:
GET /objecttype1-1/ returns:
<?xml version="1.0" encoding="UTF-8"?>
<objecttype1 xmlns="path">
<id>1</id>
<description>obj1</description>
</objecttype1>
and:和:
GET /objecttype2-3 returns:
<?xml version="1.0" encoding="UTF-8"?>
<objecttype2 xmlns="path">
<id>3</id>
<address>home</address>
</objecttype2>
Since the sub-elements are not guaranteed to be the same (other than id), I figured a List with @XmlMixed
@XmlAnyElement
will take care of them.由于不能保证子元素相同(id 除外),我认为带有
@XmlMixed
@XmlAnyElement
的 List 会处理它们。 But how do I map the root elements?但是如何映射根元素呢?
@XmlRootElement(name="???")
Due to technology limitations, I'm not able to use EclipseLink/MOXy.由于技术限制,我无法使用 EclipseLink/MOXy。 Thanks.
谢谢。
Its been 5 years since this question was asked but I found working solution of the issue, sharing for the community.问这个问题已经 5 年了,但我找到了这个问题的可行解决方案,为社区分享。
First we define JAXB beans as follows:首先我们定义JAXB bean如下:
@XmlRootElement(name = "objecttype1")
@XmlAccessorType(XmlAccessType.NONE)
public class Objecttype1 {
@XmlElement(name = "id")
private String id;
@XmlElement(name = "description")
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@XmlRootElement(name = "objecttype2")
@XmlAccessorType(XmlAccessType.NONE)
public class Objecttype2 {
@XmlElement(name = "id")
private String id;
@XmlElement(name = "address")
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setDescription(String address) {
this.address = address;
}
}
Next we need the JAXB context and the unmarshaller itself:接下来我们需要 JAXB 上下文和解组器本身:
private static final JAXBContext jaxbContext;
public Unmarshaller getUnmarshaller() {
try {
return jaxbContext.createUnmarshaller();
} catch (JAXBException ex) {
throw new IllegalStateException(ex);
}
}
Having that, the JAXB context is loading its candidates and checks if there is a match amongs them by the root element name.有了这个,JAXB 上下文就会加载它的候选对象,并通过根元素名称检查它们之间是否存在匹配。 We just unmarshal and check whats the type of received object:
我们只是解组并检查接收到的对象的类型:
try {
Object unmarshalledObject = getUnmarshaller().unmarshal(new StringReader(xmlString));
if (unmarshalledObject instanceof Objecttype1) {
//do Objecttype1 related work
} else if (unmarshalledObject instanceof Objecttype2) {
//do Objecttype2 related work
} else {
// unexpected object type
}
} catch (JAXBException ex) {
//handle ex
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.