Cameron Jones Cameron Jones - 1 month ago 12
Java Question

JAXB Unmarshalling not working. Expected elements are (none)

I am trying to unmarshal an XML.

This is what my XML looks like

<DeviceInventory2Response xmlns="http://tempuri.org/">
<DeviceInventory2Result xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Obj123 xmlns="">
<Id>1</Id>
<Name>abc</Name>
</Obj123>
<Obj456 xmlns="">
.
.
.


I am trying to get Id and Name under Obj123. However when I run my unmarshal command I get the following error.

An Error: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://tempuri.org/", local:"DeviceInventory2Response"). Expected elements are (none)


My code looks like this in the main class:

Obj123 myObj123 = (Obj123) unmarshaller.unmarshal(inputSource);


And my class for Obj123 looks like this:

package com.myProj.pkg;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


@XmlRootElement(name="Obj123")
public class Obj123 {

private String Id;
private String Name;

public String getId() {
return Id;
}

public String getName() {
return Name;
}
}


I thought by setting my XMLRootElement that I should be able to skip the first 2 lines of my XML but that doesn't seem to be happening. Any ideas?

Edit:

This is how my JAXB Context is made:

JAXBContext jaxbContext = JAXBContext.newInstance();
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Obj123 obj123 = (Obj123) unmarshaller.unmarshal(xmlStreamReader);

Answer

JAXB implementations will try to match on the root element of the document (not on a child element). If you want to unmarshal to the middle of an XML document then you can parse the document with StAX advance the XMLStreamReader to the desired element and then unmarshal that.

For More Information

UPDATE

now I am getting the following error. An Error: javax.xml.bind.UnmarshalException - with linked exception: [javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Obj123"). Expected elements are (none)].

A JAXBContext only knows about the classes you tell it about. Instead of:

JAXBContext jaxbContext = JAXBContext.newInstance();

You need to do:

JAXBContext jaxbContext = JAXBContext.newInstance(Obj123.class);