簡體   English   中英

JAXB:將不同的xml解組到同一對象

[英]JAXB: unmarshal diferent xml to same object

我有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個單獨的課程?

謝謝你的幫助

選項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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM