Jaxb Unmarshall带有未知的@XmlRootElement [英] Jaxb Unmarshall with an unknown @XmlRootElement
问题描述
我无法在不知道根元素的情况下实现解组 XML。例如。
I cannot achieve to unmarshall an XML without knowing the root element. eg.
<foo>
<bar/>
</foo>
或
<bar>
<bar/>
</bar>
等......
我想要在类上映射解组结果:
I want to map the unmarshalling result on a class like :
// @XmlRootElement ??
public class Container
implements Serializable
{
private Bar bar;
}
我总是需要修复 @XmlRootElement
。
我搜索了如何在运行时设置@XmlRootElement但没有成功。有什么想法?
I am always required to fix the @XmlRootElement
.
I searched how to set the @XmlRootElement at runtime without success. Any idea?
我在Spring Batch上下文中,我可以使用我选择的unmarshaller。
I am in Spring Batch context and I can use the unmarshaller of my choice.
注意:我不能使用 @XmlElementDecl
或 ObjectFactory
,如图所示这里因为我不知道可能的根名称的名称。
Note : I cannot use @XmlElementDecl
or an ObjectFactory
as shown here because I don't know the name of the possibles root names.
推荐答案
改编他的方法: 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());
}
}
一切正常!
这篇关于Jaxb Unmarshall带有未知的@XmlRootElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!