Jaxb Unmarshall with an unknown @XmlRootElement

三世轮回 提交于 2019-12-06 03:34:45
Adriaan Koster

Adapted his approach: https://stackoverflow.com/a/33824472/181336

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;

public class Test {

    @XmlAccessorType(XmlAccessType.PROPERTY)
    public static class Bar {
        private String name;

        public String getName() {
            return name;
        }

        @XmlElement
        public void setName(String name) {
            this.name = name;
        }
    }

    @XmlAccessorType(XmlAccessType.PROPERTY)
    public static class Container implements Serializable {
        private Bar bar;

        public Bar getBar() {
            return bar;
        }

        @XmlElement
        public void setBar(Bar bar) {
            this.bar = bar;
        }
    }

    public static void main(String[] args) throws Exception {
        JAXBContext jaxbContext = JAXBContext.newInstance(Container.class);
        String xml = "<foo><bar><name>Barry</name></bar></foo>";
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        InputStream is = new ByteArrayInputStream(xml.getBytes());
        JAXBElement<Container> barWrapperElement = unmarshaller.unmarshal(new StreamSource(is), Container.class);
        Container container = barWrapperElement.getValue();

        System.out.println(container.getBar().getName());
    }
}

It works!

Which ever XML your passing does have a root elements, xml which you mentioned have two file

<foo>
  <bar/>
</foo>

or

<bar>
 <bar/>

so here you have two root names foo or bar so create two classes for each if which ever root name it will call that class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!