Skip to main content

multiple namespaces in same package

Please note these forums are being decommissioned and use the new and improved forums at
No replies
Joined: 2013-04-01


I'm new to using namespaces in xml so I am kind of confused and would like some clarification. I have a java service where I am receiving xml documents with many different namespaces and while i got it working, I feel like I must have done something wrong so I want to check. In my I have my schema annotation such as:

@javax.xml.bind.annotation.XmlSchema(xmlns={@javax.xml.bind.annotation.XmHS(prefix="train", namespaceURI="http://mycompany/train"), @javax.xml.bind.annotation.XmHS(prefix="passenger", namespaceURI="http://mycompany/passenger")}), elementFormDefault = javax.xml.bind.annotation.XmlNsForm=QUALIFIED)

I have a annotated on the class level with:
@XmlRootElement(name="Train", namespace="http://mycompany/train")

and each field in the class annotated with:
@XmlElement(name="Color") for example

Train contains a List of Passenger(s) so there's a property
private Set passengers;

and this collection is annotated with:
@XmlElements(@XmlElement(name="Passenger", namespace="http://mycompany/passenger"))

Then within the class itself is annotated with:
@XmlElement(name="Passenger", namespace="http://mycompany/passenger")

Finally for individual fields within, they are annotated like this:
@XmlElement(name="TicketNumber", namespace="http://mycompany/passenger")

So when I have an xml that looks like:


Now I unmarshal this xml I received and Train's Color property is set and Passenger's TicketNumber property is set. But I don't know why I need to add the namespace url on the XmlElement annotation on TicketNumber for that to work but I didn't need to do so for the Color property on Train. If I remove the namespace attribute from the XmlElement annotation on TicketNumber, the value from the xml wont get mapped to the object unless I also remove the namespace prefix from the xml request. I feel like since I've got the namespace attribute defined on the XmlRootElement for Passenger, I shouldn't need to do that for every single field in the class as well just like I didn't have to for Train so I am assuming I must have setup something wrong. Can someone point me in the right direction? Thanks!