JAXB:将不同的xml解组为同一个对象

时间:2017-04-17 23:40:17

标签: java xml jaxb unmarshalling

我有3个输入XML,几乎有相同的元素和属性,事实上,它们代表相同的东西,所以我想将它们编组到同一个对象,如下所示:

请求一:

<?xml version="1.0" encoding="UTF-8"?>
<RequestOne>
    <id>123</id>
    <name>foo</name>
</RequestOne>

请求二:

<?xml version="1.0" encoding="UTF-8"?>
<RequestTwo>
    <id>123</id>
    <value>val</value>
</RequestTwo>

请求三:

<?xml version="1.0" encoding="UTF-8"?>
<RequestThree>
    <name>foo</name>
    <value>val</value>
</RequestThree>

所需对象(类似):

@XmlRootElement
public class Resource{

    @XmlElement
    private String id;
    @XmlElement
    private String name;
    @XmlElement
    private String value;

    //(...) more code
}

但是我不能使用多个RootElement注释来要求JAXB解除对类Resource

对象的所有3个请求的解组

有办法吗?或者我必须制作3个sepparated类?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

选项1

使用重载的通用unmarshal方法解组:

public static class Base {
    private String name ;

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public Base setName(String name) {
        this.name = name;
        return this;
    }
}

public static void main (String [] args) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Base.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    JAXBElement<Base> basea = unmarshaller.unmarshal(new StreamSource(new StringReader("<RootA><name>nanana</name></RootA>")), Base.class);
    System.out.println(basea.getValue().getName());
    JAXBElement<Base> baseb = unmarshaller.unmarshal(new StreamSource(new StringReader("<RootB><name>nbnbnb</name></RootB>")), Base.class);
    System.out.println(baseb.getValue().getName());
}

选项2

您总是可以使用Java的类子类型功能吗? JAXB也对父类进行注释扫描。此示例有效

public static class Base {
    private String name ;

    @XmlElement(name = "name")
    public String getName() {
        return name;
    }

    public Base setName(String name) {
        this.name = name;
        return this;
    }
}

@XmlRootElement( name = "RootA")
public static class RootA extends Base{ 
}

@XmlRootElement( name = "RootB")
public static class RootB extends Base {
}


public static void main (String [] args) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(RootA.class,RootB.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    RootA rootA = (RootA)unmarshaller.unmarshal(new StringReader("<RootA><name>nanana</name></RootA>"));
    System.out.println(rootA.getName());
    RootB rootB = (RootB)unmarshaller.unmarshal(new StringReader("<RootB><name>nbnbnb</name></RootB>"));
    System.out.println(rootB.getName());
}