Home > Software design >  Jaxb java set namespace to all elements
Jaxb java set namespace to all elements

Time:04-07

I have a Java class:

@XmlRootElement(name = "a")
public class a {
    @XmlElementWrapper
    public Component[] components;

    public String content;
}

And an XML file: test.xml and XSD file which is generated using the JAXBContext::generateSchema method.

An example XML file:

<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://example.com"
      xsi:schemaLocation="http://example.com file://...schema.xsd">
</a>

If I want to unmarshal it, I need to add namespace = "http://example.com" to all elements.
Otherwise, I will get a javax.xml.bind.UnmarshalException as this.
However, If I have a lot of classes in many different packages, or some fields that are annotated with @XmlElements has a lot of @XmlElement children.
I need to copy and paste namespace = "http://example.com" uncountable times, it is dumb and meaningless. Are there some methods that allow me to only type the namespace once?

CodePudding user response:

You can try to add file: package-info.java to your package.

@javax.xml.bind.annotation.XmlSchema(namespace = 
"http://webservices.com/myws",
   xmlns = { 
       @javax.xml.bind.annotation.XmlNs(prefix = "ws", 
       namespaceURI="http://webservices.com/myws")
   } 
)
package mypackage;
  • Related