2011-02-25 64 views
8

我有一个web服务调用。在我的回应中,当我尝试将xml any元素放入JAXBElement中时,它会引发错误。JAXB不将unmarshalling xml任何元素添加到JAXBElement

在架构,我有:

<xs:complexType name="InputType"> 
    <xs:annotation></xs:annotation> 
    <xs:sequence>   
     <xs:element name="Id" type="xs:string" /> 
     <xs:any namespace="##any" processContents="lax" minOccurs="0" /> 
    </xs:sequence> 
</xs:complexType> 

的代码我使用:

Object obj = inputType.getAny(); 
Object o = ((JAXBElement)obj).getValue(); 

此行引发错误:在肥皂UI org.apache.xerces.dom.ElementNSImpl incompatible with javax.xml.bind.JAXBElement错误。

为什么它不转化为JAXBElement?我如何使它工作?

回答

1

根据您的模式验证您的xml。应该是这样的,首先要检查

9

如果该属性具有以下将被映射为DOM的内容注释节点:

@XmlAnyElement 

如果不严= true标志被设置,那么众所周知的元件将转换成域对象:

@XmlAnyElement(lax=true) 

有关详细信息上@XmlAnyElement看到:


更新#1

不严= TRUE,你可以得到的域对象和DOM节点的混合。以下是从Java文档:

When true

If true, when an element matches a property marked with XmlAnyElement is known to JAXBContext (for example, there's a class with XmlRootElement that has the same tag name, or there's XmlElementDecl that has the same tag name), the unmarshaller will eagerly unmarshal this element to the JAXB object, instead of unmarshalling it to DOM. Additionally, if the element is unknown but it has a known xsi:type, the unmarshaller eagerly unmarshals the element to a JAXBElement, with the unknown element name and the JAXBElement value is set to an instance of the JAXB mapping of the known xsi:type.

As a result, after the unmarshalling, the property can become heterogeneous; it can have both DOM nodes and some JAXB objects at the same time.


更新#2

为了最终解决问题:

  1. 由于该属性可能包含DOM节点,因此您的代码应通过执行某种类型检查来解决此问题。
  2. 要减少接收到的DOM节点的数量,您需要将这些片段的可能根元素与Java类相关联。这是通过使用@XmlRootElement(name =“foo”,namespace =“bar”)或@XmlElementDecl注释类来完成的。

看看我的博客为例:

+0

在这种情况下,它是松懈=真,领域对象。但我的问题是为什么解组抱怨与JAXBElement对象不兼容。 – valve2010 2011-02-25 20:56:41

+0

您仍然可以在使用@XmlAnyElement(lax = true)注解的属性中获取DOM节点。查看更新的答案。 – 2011-02-25 21:01:51

+0

感谢您提供的信息,我如何从这个getAny()中获取值。解决方法是什么? – valve2010 2011-02-25 21:19:48