JAXB: How to ignore namespace during unmarshalling XML document?

java, jaxb, xml, xml-serialization

Solution

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

- Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.

- Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

Problem

My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)? In other words, I have ``` <foo><bar></bar></foo> ``` instead of, ``` <foo xmlns="http://tempuri.org/"><bar></bar></foo> ```

Original source

Related problems