JannaBotna
JannaBotna

Reputation: 27

UnmarshalException error

I'm trying to unmarshal my DOM parsed document so that I can update my XML. But I got the following namespace error:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Showing_Today"). Expected elements are <{http://xml.netbeans.org/schema/Shows}Showing_Today>

Here is my: package-info.java

@javax.xml.bind.annotation.XmlSchema
(namespace = "http://xml.netbeans.org/schema/Shows", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) 
package Media;

Here is my XML file that I'm trying to unmarshal:

  <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
 <Showing_Today xmlns="http://xml.netbeans.org/schema/Shows">
 <movie_collection>
  <Title>Red</Title> 
  <Director>Robert Schwentke</Director> 
  <Year>2010</Year> 
  </movie_collection>

ShowingToday.java

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "movieCollection"
})
@XmlRootElement(name = "Showing_Today")
public class ShowingToday {

    @XmlElement(name = "movie_collection")
    protected List<MovieType> movieCollection;

And here is my unmarshaller code:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document domDoc = docBuilder.parse("Now_Showing.xml");
dbf.setNamespaceAware(true);

JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(ShowingToday.class);
Binder <Node> binder = jaxbCtx.createBinder();
Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
ShowingToday shows2 = (ShowingToday) binder.unmarshal(domDoc);

I've looked at many similar questions, but none of the solutions helped. Any suggestions on how I can fix it? Thank you

Upvotes: 1

Views: 588

Answers (1)

Michael Glavassevich
Michael Glavassevich

Reputation: 1040

You need to call setNamespaceAware() before you create the DocumentBuilder. Setting this after you've created the parser and built the DOM will have no effect. That's very likely the reason why JAXB is unable to unmarshal the root element, as it would be missing its namespace.

Try this:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document domDoc = docBuilder.parse("Now_Showing.xml");

Upvotes: 2

Related Questions