使用JAXB使用动态根元素解组XML

时间:2015-05-19 23:09:47

标签: java xml jaxb

我正在尝试与第三方系统集成,并且根据对象的类型,返回的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。感谢。

1 个答案:

答案 0 :(得分: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
}