Reputation: 4476
I'm currently working on marshalling/unmarshalling XML messages. Here are my two XML elements :
@XmlRootElement(namespace = "http://namespaceA")
public class RootElementA {
@XmlElement
private ElementXX elementXX;
}
@XmlRootElement(namespace = "http://namespaceB")
public class RootElementB {
@XmlElement
private ElementXX elementXX;
}
When unmarshalling a RootElementB I have the following error :
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://namespaceB", local:"ElementXX"). Expected elements are <{}ElementXX>
If I add the namespace to the ElementXX declaration, I have the same error except that it occurs for properties of ElementXX.
The problem is that I can't set the namespace on properties of ElementXX because it is specified in both namespaces and I don't want to duplicate my class just to change the namespace...
Do you have an idea ? Thanks.
EDIT
Here is a XML sample :
<RootElementA xmlns="http://namespaceA">
<ElementXX>
<name>blabla</name>
<desc>blabla</desc>
</ElementXX>
</RootElementA>
If I don't set a namespace to ElementXX in XmlRootElementA class I have the error above. If I set it, I have the same error but for the name property.
Upvotes: 2
Views: 6022
Reputation: 149057
You can use the @XmlSchema
annotation to specify the namespace qualification for classes and properties within a package. You can specify the namespace for the properties of a class by specifying the namespace on @XmlType
. Then you can specify the namespace for a so single element/attribute using @XmlRootElement
, @XmlElement
, and @XmlAttribute
.
For More Information
Upvotes: 0
Reputation: 666
You can remove the @XmlElement
annotation for ElementXX
. As long as it has a public getter, default behavior is to marshal it as well.
The XML should then look like this.
<ns3:rootElementB xmlns:ns2="http://namespaceA" xmlns:ns3="http://namespaceB">
<elementXX/>
</ns3:rootElementB>
An alternative is to declare the namespace of ElementXX
in its java class using @XmlRootElement
similar to RootElementA and B. Then replacing @XmlElement
with @XmlElementRef
in RootElementA and B.
XML would then look like this: (Note: I added the field name for the test)
<ns4:rootElementB xmlns:ns2="http://namespaceXX" xmlns:ns3="http://namespaceA" xmlns:ns4="http://namespaceB">
<ns2:elementXX>
<name>test</name>
</ns2:elementXX>
</ns4:rootElementB>
I was not able to exactly reproduce your error. I think, however, that having ElementXX
declared in two namespaces is not advisable, to say the least. If you can modify your Schemas, I suggest creating a new one with its own namespace and declaring ElementXX
in it. Then modify the other two to reference its elements.
Upvotes: 1
Reputation: 2488
you didnt have xml here to have a look.. but i guess the below link will give you an answer.
XML unmarshalling using Jaxb with namespaces and schema
if not post the xml you are trying to unmarshall.
Upvotes: 0