gpt4 book ai didi

java - 使用 JAXB 使用动态根元素解码 XML

转载 作者:行者123 更新时间:2023-12-01 05:04:36 27 4
gpt4 key购买 nike

我正在尝试与第三方系统集成,并且根据对象的类型,返回的 XML 文档的根元素会发生变化。例如:

GET /objecttype1-1/ returns:
<?xml version="1.0" encoding="UTF-8"?>
<objecttype1 xmlns="path">
<id>1</id>
<description>obj1</description>
</objecttype1>

和:
GET /objecttype2-3 returns:
<?xml version="1.0" encoding="UTF-8"?>
<objecttype2 xmlns="path">
<id>3</id>
<address>home</address>
</objecttype2>

由于不能保证子元素相同(除了 id),我想出了一个带有 @XmlMixed 的列表 @XmlAnyElement会照顾他们。但是如何映射根元素呢? @XmlRootElement(name="???")
由于技术限制,我无法使用 EclipseLink/MOXy。谢谢。

最佳答案

问这个问题已经 5 年了,但我找到了这个问题的可行解决方案,为社区分享。

首先我们定义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;
}
}

接下来我们需要 JAXB 上下文和解码器本身:
private static final JAXBContext jaxbContext;

public Unmarshaller getUnmarshaller() {
try {
return jaxbContext.createUnmarshaller();
} catch (JAXBException ex) {
throw new IllegalStateException(ex);
}
}

有了这个,JAXB 上下文就会加载它的候选对象,并通过根元素名称检查它们之间是否存在匹配。我们只是解码并检查接收到的对象的类型:
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
}

关于java - 使用 JAXB 使用动态根元素解码 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30337646/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com