Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB unmarshalling error: Expected elements are <{ } Root>

I'm reusing existing objects generated elsewhere to unmarshall XML data coming in as a String type.

The object:

/*  3:   */ import java.util.ArrayList;
/*  4:   */ import java.util.List;
/*  5:   */ import javax.xml.bind.annotation.XmlAccessType;
/*  6:   */ import javax.xml.bind.annotation.XmlAccessorType;
/*  7:   */ import javax.xml.bind.annotation.XmlElement;
/*  8:   */ import javax.xml.bind.annotation.XmlRootElement;
/*  9:   */ import javax.xml.bind.annotation.XmlType;
/* 10:   */ 
/* 11:   */ @XmlAccessorType(XmlAccessType.FIELD)
/* 12:   */ @XmlType(name="", propOrder={"policy"})
/* 13:   */ @XmlRootElement(name="MyNodeResponse")
/* 14:   */ public class MyNodeResponse
/* 15:   */ {
/* 16:   */   @XmlElement(name="Policy")
/* 17:   */   protected List<Policy> policy;
/* 18:   */   
/* 19:   */   public List<Policy> getPolicy()
/* 20:   */   {
/* 21:65 */     if (this.policy == null) {
/* 22:66 */       this.policy = new ArrayList();
/* 23:   */     }
/* 24:68 */     return this.policy;
/* 25:   */   }
/* 26:   */ }

My unmarshalling code:

JAXBContext jc = JAXBContext.newInstance(MyNodeResponse.class); 
Unmarshaller unmarshaller = jc.createUnmarshaller();
MyNodeResponse myNodeResponse = (MyNodeResponse)unmarshaller.unmarshal(new InputSource(new ByteArrayInputStream(xmlStringInput.getBytes("utf-8"))));

My input XML:

<ns2:MyNodeResponse 
         xmlns:ns2="mynamespace/2010/10">   
   <ns2:Policy>
   ....more data....
   <ns2:Policy/>
<ns2:MyNodeResponse />

I get the following error when unmarshalling:

unexpected element (uri:"mynamespace/2010/10", local:"MyNodeResponse"). Expected elements are <{}MyNodeResponse>

What exactly does the "{ }" refer to in the error, and how do I unmarshall in a way to match what is present in the input XML and how the object is expecting?

like image 736
JWiley Avatar asked Mar 11 '14 19:03

JWiley


1 Answers

What the Error Message is Saying

What exactly does the "{ }" refer to in the error

In {}MyNodeRespons the {} portion refers to that qualified name not having the namespace URI portion set.

How to Fix It

You need to map the namespace qualification using the package level @XmlSchema annotation:

package-info.java

@XmlSchema(
    namespace = "mynamespace/2010/10",
    elementFormDefault = XmlNsForm.QUALIFIED)
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

For More Information

  • http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
like image 120
bdoughan Avatar answered Sep 29 '22 16:09

bdoughan