If your XML schema indicates that the corresponding XML documents should have a namespace, then JAXB will generate a Java model with the expected qualification of the namespace. Below I will describe the way you could use the StAX parser to trick JAXB into believing that it parses a document with a namespace request:
Player
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name="Player", namespace="http://www.example.org/Player") public class Player { private String login; private String passwd; @XmlElement(name="Login", namespace="http://www.example.org/Player") public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } @XmlElement(name="Passwd", namespace="http://www.example.org/Player") public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } }
NamespaceDelegate
We will create an implementation of StreamReaderDelegate . This delegate will report that the namespace for all events of the element will be "http://www.example.org/Player" . Note. This trick assumes that all of your elements have the same namespace URI.
import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.StreamReaderDelegate; public class NamespaceDelegate extends StreamReaderDelegate { private static String NAMESPACE = "http://www.example.org/Player"; public NamespaceDelegate(XMLStreamReader xsr) { super(xsr); } @Override public String getNamespaceURI() { return NAMESPACE; } }
Demo
import java.io.FileInputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.StreamReaderDelegate; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Player.class); FileInputStream xmlStream = new FileInputStream("input.xml"); XMLInputFactory xif = XMLInputFactory.newFactory(); XMLStreamReader xsr = xif.createXMLStreamReader(xmlStream); StreamReaderDelegate srd = new NamespaceDelegate(xsr); Unmarshaller unmarshaller = jc.createUnmarshaller(); Player player = (Player) unmarshaller.unmarshal(srd); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(player, System.out); } }
Input.xml
<?xml version="1.0" encoding="UTF-8"?> <Player> <Login>FOO</Login> <Passwd>BAR</Passwd> </Player>
source share