JAXB解组错误:预期的元素是<{} Root>

JWi*_*ley 3 java xml namespaces jaxb unmarshalling

我正在重用其他地方生成的现有对象来解组以String类型形式出现的XML数据.

物体:

/*  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:   */ }
Run Code Online (Sandbox Code Playgroud)

我的解组代码:

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

我的输入XML:

<ns2:MyNodeResponse 
         xmlns:ns2="mynamespace/2010/10">   
   <ns2:Policy>
   ....more data....
   <ns2:Policy/>
<ns2:MyNodeResponse />
Run Code Online (Sandbox Code Playgroud)

解组时我收到以下错误:

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

"{}"究竟在错误中引用了什么,以及如何以匹配输入XML中存在的内容以及对象期望的方式进行解组?

bdo*_*han 13

错误消息说的是什么

"{}"究竟在错误中引用了什么

{}MyNodeRespons{}部分中指的是没有设置名称空间URI部分的限定名称.

如何解决它

您需要使用包级别@XmlSchema注释映射命名空间限定:

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;
Run Code Online (Sandbox Code Playgroud)

欲获得更多信息