使用JAXB解析具有动态根元素的XML

4

我正在尝试与第三方系统集成,根据对象类型,返回的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的List可以解决它们。但是如何映射根元素?@XmlRootElement(name="???")

由于技术限制,我无法使用EclipseLink/MOXy。谢谢。


你解决了上述问题吗?我曾经处于类似的情况。 - Siddharth Trikha
1个回答

1

这个问题已经被提出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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接