Ste*_*and 27 java jaxb unmarshalling
我有两个代码,在两个不同的java项目中,做了几乎相同的事情,(根据xsd文件解组webservice的输入).
但在一种情况下我应该这样写:(输入是一个占位符名称)(元素是OMElement输入)
ClassLoader clInput = input.ObjectFactory.class.getClassLoader();
JAXBContext jc = JAXBContext.newInstance("input", clInput);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() );
Run Code Online (Sandbox Code Playgroud)
在另一个lib中,我必须使用JAXBElement.getValue(),因为它是一个返回的JAXBElement,一个简单的(Input)转换只是崩溃:
Input input = (Input)unmarshaller.unmarshal( element.getXMLStreamReader() ).getValue();
Run Code Online (Sandbox Code Playgroud)
你知道是什么导致了这样的差异吗?
bdo*_*han 25
如果根元素唯一对应于Java类,则将返回该类的实例,如果不是,JAXBElement
则返回.
如果您想确保始终获得域对象的实例,则可以利用JAXBInstrospector
.以下是一个例子.
演示
package forum10243679;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
private static final String XML = "<root/>";
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBIntrospector jaxbIntrospector = jc.createJAXBIntrospector();
Object object = unmarshaller.unmarshal(new StringReader(XML));
System.out.println(object.getClass());
System.out.println(jaxbIntrospector.getValue(object).getClass());
Object jaxbElement = unmarshaller.unmarshal(new StreamSource(new StringReader(XML)), Root.class);
System.out.println(jaxbElement.getClass());
System.out.println(jaxbIntrospector.getValue(jaxbElement).getClass());
}
}
Run Code Online (Sandbox Code Playgroud)
产量
class forum10243679.Root
class forum10243679.Root
class javax.xml.bind.JAXBElement
class forum10243679.Root
Run Code Online (Sandbox Code Playgroud)
这取决于根元素的类上是否存在XmlRootElement 注释。
如果您从 XSD 生成 JAXB 类,则应用以下规则:
因此,我经常为根元素选择匿名类型。
您可以使用自定义文件自定义此匿名类型的类名。例如创建一个 bindings.xjc 文件,如下所示:
<jxb:bindings version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:bindings schemaLocation="yourXsd.xsd" node="/xs:schema">
<jxb:bindings node="//xs:element[@name='yourRootElement']">
<jxb:class name="YourRootElementType"/>
</jxb:bindings>
</jxb:bindings>
</jxb:bindings>
Run Code Online (Sandbox Code Playgroud)