使用JAXB进行XML解组,字段类型基于XML属性值?

时间:2018-06-27 13:19:25

标签: java xml jaxb unmarshalling xml-attribute

我的应用程序从另一个应用程序接收以下形式的xml:

<targetedMessage>
    <sender>the sender</sender>
    <payload class="other.app.classpath.Foo">
        <id>1</id>
    </payload>
</targetedMessage>

其中Foo是我的模块和另一个应用程序中都存在的几个类中的任何一个,并且实现了一个公共接口:

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class Foo implements MyInterface {
    private long id;
    \\ getters and setters
}

TargetedMessage类是:

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class TargetedMessage {
    private String sender;
    private MyInterface payload;
    \\ getters and setters
}

我有一个枚举,它将其他应用程序的类路径映射到我的模块中的类:

public enum MyClasses {
    FOO(Foo.class, "other.app.classpath.Foo"),
    BAR(Bar.class, "other.app.classpath.Bar"),
    \\ ...
}

使用JAXB,可以解组xml,以使有效载荷具有正确的类型(在上述情况下,有效载荷类为Foo)。

1 个答案:

答案 0 :(得分:0)

我不了解JAXB,但SimpleXml可以做到:

@XmlName("targetedMessage")
public class TargetedMessage {
    String sender;
    @XmlAbstactClass(attribute="class", types={
        @TypeMap(name="other.app.classpath.Foo", type=Foo.class),
        @TypeMap(name="other.app.classpath.Bar", type=Bar.class)
    })
    Payload payload;
}
interface Payload {}
public class Foo implements Payload {
    Integer id;
}
public class Bar implements Payload {
    String name;
}

final String data = ...

final SimpleXml simple = new SimpleXml();
final TargetedMessage message = simple.fromXml(data, TargetedMessage.class);
System.out.println(message.payload.getClass().getSimpleName());
System.out.println(((Foo)message.payload).id);

将输出:

Foo
1

从Maven Central:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.5.0</version>
</dependency>