Count
Count

Reputation: 1423

Optional Namespace parsing XML via JAXB

In my application user uploads several XMLs. Few XMLs that are uploaded do not contain a namespace tag and others contain it. I want to be able to support upload for both. JAXB is giving exception on former.

I want to able able to make namespace as optional ie support both files.

XML that is working

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ns2:transforms xmlns:ns2="http://www.mynamesapace.com/xmlbeans/connectorconfig">

XML that is failing

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<transforms>

Here is how I am unmarshalling the XML

  JAXBContext jaxbContext = JAXBContext.newInstance(Transforms.class);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  transforms = (Transforms) jaxbUnmarshaller.unmarshal(file);

This is my pojo

@XmlRootElement(name = "transforms", namespace = 
"http://www.mynamesapace.com/xmlbeans/connectorconfig")
public class Transforms implements ConfigDiffable<Transforms, 
ChangedTransforms> {
.....

Update :

If I remove

namespace = 
    "http://www.mynamesapace.com/xmlbeans/connectorconfig"

XML without namespace start working

Upvotes: 0

Views: 480

Answers (1)

Roger Gustavsson
Roger Gustavsson

Reputation: 1719

Create a class:

class XMLReaderWithoutNamespace extends StreamReaderDelegate {
  public XMLReaderWithoutNamespace(XMLStreamReader reader) {
    super(reader);
  }

  @Override
  public String getAttributeNamespace(int arg0) {
    return "";
  }

  @Override
  public String getNamespaceURI() {
    return "";
  }
}

Change your unmarshalling to:

JAXBContext jaxbContext = JAXBContext.newInstance(Transforms.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
InputStream is = new FileInputStream(file);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
transforms = (Transforms) jaxbUnmarshaller.unmarshal(xr);

I had no namespace defined in the pojo when I tested this.

Solution taken from this answer.

Upvotes: 1

Related Questions