So, lets say I have this xml with several namespaces.
<Envelope xmlns:pdi="http://www.mypage.com/schemas/pdi" xmlns:ib="http://www.mypage.com/schemas/ib" xmlns="http://www.mypage.com/schemas/envelope">
<Product>
<pdi:number>123456</pdi:number>
</Product>
<Instance>
<ib:serial>abcdefg</ib:serial>
</Instance>
</Envelope>
I'm trying to build a client for it. I have an Envelope POJO that's declared like this
@XmlRootElement(name ="Envelope", namespace = "http://www.mypage.com/schemas/envelope")
public class Envelope
and inside, it has these attributes
@XmlElement(name="Product", namespace = "http://www.mypage.com/schemas/pdi")
public Product getProduct(){...}
@XmlElement(name="Instance", namespace = "http://www.mypage.com/schemas/ib")
public Instance getInstance(){...}
Also, the Product POJO looks like this:
@XmlRootElement(name="Product", namespace = "http://www.mypage.com/schemas/pdi")
public class Product
and attribute
@XmlElement(name="pdi:number", namespace = "http://www.mypage.com/schemas/pdi")
public int getNumber(){...}
For some reason, I can't get the product number. I keep getting a request error. Am I handling the namespaces correctly, or am I missing something?
For this use case I would recommend leveraging the package level
@XmlSchema
annotation to specify the namespace qualification.package-info (forum14651918/package-info.java)
Envelope (forum14651918/Envelope.java)
Since we have specified a
namespace
andelementFormDefault
on the@XmlSchema
annotation, all the elements corresponding to theEnvelope
class will be automatically qualified with thehttp://www.mypage.com/schemas/envelope
namespace.Product (forum14651918/Product.java)
You can override the namespace for the
Product
class using the@XmlType
annotation.Instance (forum14651918/Instance.java)
You can override the namespace for the
Instance
class using the@XmlType
annotation.Demo (forum14651918/Demo.java)
Below is some code you can run to prove that everything works.
For More Information
Try replacing
name="pdi:number", namespace = "http://www.mypage.com/schemas/pdi"
withname="number", namespace = "http://www.mypage.com/schemas/pdi"
. Prefix is not needed.What is more looking at the XML it seems that namespace for both
Product
andInstance
ishttp://www.mypage.com/schemas/envelope
.You should not need
@XmlRootElement
annotation forProduct
class. It is not a root element and is already configured ongetProduct()
.Full configuration that should be OK is: