2015-01-13 10 views
16

На этом сайте вы можете найти много вопросов, но никто не решил мою проблему.javax.xml.bind.UnmarshalException: неожиданный элемент (uri: "", local: ""). Ожидаемые элементы:

Это мой XML:

<?xml version='1.0' encoding='UTF-8' standalone='yes'?> 
<lookupInstances xmlns='http://www.pqr.com/awd/rest/v1' name='LKIMGR'> 
<lookupParameters> 
<lookupParameter name='businessArea'>PQAA</lookupParameter> 
<lookupParameter name='MEMBERNUMBER'>ANTHONY1900</lookupParameter> 
</lookupParameters> 
</lookupInstances> 

Я создал класс JAXB, используя XJC компилятор и файл, созданный как:

// 
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2015.01.13 at 12:15:41 PM IST 
// 


package com.dsths.ga.awd.main; 

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlAttribute; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlType; 


/** 
* <p>Java class for anonymous complex type. 
* 
* <p>The following schema fragment specifies the expected content contained within this class. 
* 
* <pre> 
* &lt;complexType> 
* &lt;complexContent> 
*  &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
*  &lt;sequence> 
*   &lt;element name="lookupParameters"> 
*   &lt;complexType> 
*    &lt;complexContent> 
*    &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
*     &lt;sequence> 
*     &lt;element name="lookupParameter"> 
*      &lt;complexType> 
*      &lt;complexContent> 
*       &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
*       &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
*       &lt;/restriction> 
*      &lt;/complexContent> 
*      &lt;/complexType> 
*     &lt;/element> 
*     &lt;/sequence> 
*    &lt;/restriction> 
*    &lt;/complexContent> 
*   &lt;/complexType> 
*   &lt;/element> 
*  &lt;/sequence> 
*  &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
*  &lt;/restriction> 
* &lt;/complexContent> 
* &lt;/complexType> 
* </pre> 
* 
* 
*/ 
@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "", propOrder = { 
    "lookupParameters" 
}) 
@XmlRootElement(name = "lookupInstances") 
public class LookupInstances { 

    @XmlElement(required = true) 
    protected LookupInstances.LookupParameters lookupParameters; 
    @XmlAttribute 
    protected String name; 

    /** 
    * Gets the value of the lookupParameters property. 
    * 
    * @return 
    *  possible object is 
    *  {@link LookupInstances.LookupParameters } 
    *  
    */ 
    public LookupInstances.LookupParameters getLookupParameters() { 
     return lookupParameters; 
    } 

    /** 
    * Sets the value of the lookupParameters property. 
    * 
    * @param value 
    *  allowed object is 
    *  {@link LookupInstances.LookupParameters } 
    *  
    */ 
    public void setLookupParameters(LookupInstances.LookupParameters value) { 
     this.lookupParameters = value; 
    } 

    /** 
    * Gets the value of the name property. 
    * 
    * @return 
    *  possible object is 
    *  {@link String } 
    *  
    */ 
    public String getName() { 
     return name; 
    } 

    /** 
    * Sets the value of the name property. 
    * 
    * @param value 
    *  allowed object is 
    *  {@link String } 
    *  
    */ 
    public void setName(String value) { 
     this.name = value; 
    } 


    /** 
    * <p>Java class for anonymous complex type. 
    * 
    * <p>The following schema fragment specifies the expected content contained within this class. 
    * 
    * <pre> 
    * &lt;complexType> 
    * &lt;complexContent> 
    *  &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
    *  &lt;sequence> 
    *   &lt;element name="lookupParameter"> 
    *   &lt;complexType> 
    *    &lt;complexContent> 
    *    &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
    *     &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
    *    &lt;/restriction> 
    *    &lt;/complexContent> 
    *   &lt;/complexType> 
    *   &lt;/element> 
    *  &lt;/sequence> 
    *  &lt;/restriction> 
    * &lt;/complexContent> 
    * &lt;/complexType> 
    * </pre> 
    * 
    * 
    */ 
    @XmlAccessorType(XmlAccessType.FIELD) 
    @XmlType(name = "", propOrder = { 
     "lookupParameter" 
    }) 
    public static class LookupParameters { 

     @XmlElement(required = true) 
     protected LookupInstances.LookupParameters.LookupParameter lookupParameter; 

     /** 
     * Gets the value of the lookupParameter property. 
     * 
     * @return 
     *  possible object is 
     *  {@link LookupInstances.LookupParameters.LookupParameter } 
     *  
     */ 
     public LookupInstances.LookupParameters.LookupParameter getLookupParameter() { 
      return lookupParameter; 
     } 

     /** 
     * Sets the value of the lookupParameter property. 
     * 
     * @param value 
     *  allowed object is 
     *  {@link LookupInstances.LookupParameters.LookupParameter } 
     *  
     */ 
     public void setLookupParameter(LookupInstances.LookupParameters.LookupParameter value) { 
      this.lookupParameter = value; 
     } 


     /** 
     * <p>Java class for anonymous complex type. 
     * 
     * <p>The following schema fragment specifies the expected content contained within this class. 
     * 
     * <pre> 
     * &lt;complexType> 
     * &lt;complexContent> 
     *  &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
     *  &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
     *  &lt;/restriction> 
     * &lt;/complexContent> 
     * &lt;/complexType> 
     * </pre> 
     * 
     * 
     */ 
     @XmlAccessorType(XmlAccessType.FIELD) 
     @XmlType(name = "") 
     public static class LookupParameter { 

      @XmlAttribute 
      protected String name; 

      /** 
      * Gets the value of the name property. 
      * 
      * @return 
      *  possible object is 
      *  {@link String } 
      *  
      */ 
      public String getName() { 
       return name; 
      } 

      /** 
      * Sets the value of the name property. 
      * 
      * @param value 
      *  allowed object is 
      *  {@link String } 
      *  
      */ 
      public void setName(String value) { 
       this.name = value; 
      } 

     } 

    } 

} 

распаковать Код:

public LookupInstances unmarshallXmlRequest(String xmlReq) 
    { 
     LookupInstances instances = null; 
      try { 
      JAXBContext jc = JAXBContext.newInstance(LookupInstances.class); 
       Unmarshaller u = jc.createUnmarshaller(); 
       StringBuffer xmlStr = new StringBuffer(xmlReq); 
       StringReader strReader = new StringReader(xmlStr.toString()); 
       StreamSource strSource = new StreamSource(strReader); 
       Object o = u.unmarshal(strSource); 
       instances = (LookupInstances)o; 
     } catch (JAXBException e) { 

      e.printStackTrace(); 
     } 
     return instances; 
    } 

Я получил эту ошибку:

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.pqr.com/awd/rest/v1", local:"lookupInstances"). Expected elements are <{}lookupInstances> 

Просьба помочь.

ответ

1

кажется, что класс, созданный JAXB не содержит информацию о пространстве имен:

@XmlType(name = "", propOrder = { 
    "lookupParameters" 
}) 

Я подозреваю, что он вызывает эту ошибку, просто потому, что не ожидает имен:

javax. xml.bind.UnmarshalException: неожиданный элемент (uri: "http://www.pqr.com/awd/rest/v1", local: "lookupInstances"). Ожидаемые элементы < {} lookupInstances>

Я не уверен, почему сгенерированный класс не хватает этой информации, но я хотел бы начать с добавлением его вручную, чтобы убедиться, что это проблема:

@XmlType(name = "", namespace= "http://www.pqr.com/awd/rest/v1", propOrder = { 
    "lookupParameters" 
}) 
+0

Благодарим за быстрый ответ @Magnilex. Как вы предположили, я добавил пространство имен в объявление класса Java и ошибка исчезла. Но в то время как unmarshaling класс java, он не содержит всех элементов или неправильно инициализирован. Я изменил класс jaxb, который теперь содержит List для захвата ** lookupParameter ** и теперь он работает. – Rana

+0

@ Rana Рад помочь, и хорошо, что мой ответ подтолкнул вас в правильном направлении. – Magnilex

2

Я изменил класс jaxb, изменив xsd, и теперь он работает.

// 
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2015.01.13 at 03:49:52 PM IST 
// 


package com.dsths.ga.awd.main; 

import java.util.ArrayList; 
import java.util.List; 
import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlAttribute; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlType; 
import javax.xml.bind.annotation.XmlValue; 


/** 
* <p>Java class for anonymous complex type. 
* 
* <p>The following schema fragment specifies the expected content contained within this class. 
* 
* <pre> 
* &lt;complexType> 
* &lt;complexContent> 
*  &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
*  &lt;sequence> 
*   &lt;element name="lookupParameters"> 
*   &lt;complexType> 
*    &lt;complexContent> 
*    &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
*     &lt;sequence> 
*     &lt;element name="lookupParameter" maxOccurs="unbounded" minOccurs="0"> 
*      &lt;complexType> 
*      &lt;simpleContent> 
*       &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string"> 
*       &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
*       &lt;/extension> 
*      &lt;/simpleContent> 
*      &lt;/complexType> 
*     &lt;/element> 
*     &lt;/sequence> 
*    &lt;/restriction> 
*    &lt;/complexContent> 
*   &lt;/complexType> 
*   &lt;/element> 
*  &lt;/sequence> 
*  &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
*  &lt;/restriction> 
* &lt;/complexContent> 
* &lt;/complexType> 
* </pre> 
* 
* 
*/ 
@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "", propOrder = { 
    "lookupParameters" 
}) 
@XmlRootElement(name = "lookupInstances") 
public class LookupInstances { 

    @XmlElement(required = true) 
    protected LookupInstances.LookupParameters lookupParameters; 
    @XmlAttribute(name = "name") 
    protected String name; 

    /** 
    * Gets the value of the lookupParameters property. 
    * 
    * @return 
    *  possible object is 
    *  {@link LookupInstances.LookupParameters } 
    *  
    */ 
    public LookupInstances.LookupParameters getLookupParameters() { 
     return lookupParameters; 
    } 

    /** 
    * Sets the value of the lookupParameters property. 
    * 
    * @param value 
    *  allowed object is 
    *  {@link LookupInstances.LookupParameters } 
    *  
    */ 
    public void setLookupParameters(LookupInstances.LookupParameters value) { 
     this.lookupParameters = value; 
    } 

    /** 
    * Gets the value of the name property. 
    * 
    * @return 
    *  possible object is 
    *  {@link String } 
    *  
    */ 
    public String getName() { 
     return name; 
    } 

    /** 
    * Sets the value of the name property. 
    * 
    * @param value 
    *  allowed object is 
    *  {@link String } 
    *  
    */ 
    public void setName(String value) { 
     this.name = value; 
    } 


    /** 
    * <p>Java class for anonymous complex type. 
    * 
    * <p>The following schema fragment specifies the expected content contained within this class. 
    * 
    * <pre> 
    * &lt;complexType> 
    * &lt;complexContent> 
    *  &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> 
    *  &lt;sequence> 
    *   &lt;element name="lookupParameter" maxOccurs="unbounded" minOccurs="0"> 
    *   &lt;complexType> 
    *    &lt;simpleContent> 
    *    &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string"> 
    *     &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
    *    &lt;/extension> 
    *    &lt;/simpleContent> 
    *   &lt;/complexType> 
    *   &lt;/element> 
    *  &lt;/sequence> 
    *  &lt;/restriction> 
    * &lt;/complexContent> 
    * &lt;/complexType> 
    * </pre> 
    * 
    * 
    */ 
    @XmlAccessorType(XmlAccessType.FIELD) 
    @XmlType(name = "", propOrder = { 
     "lookupParameter" 
    }) 
    public static class LookupParameters { 

     protected List<LookupInstances.LookupParameters.LookupParameter> lookupParameter; 

     /** 
     * Gets the value of the lookupParameter property. 
     * 
     * <p> 
     * This accessor method returns a reference to the live list, 
     * not a snapshot. Therefore any modification you make to the 
     * returned list will be present inside the JAXB object. 
     * This is why there is not a <CODE>set</CODE> method for the lookupParameter property. 
     * 
     * <p> 
     * For example, to add a new item, do as follows: 
     * <pre> 
     * getLookupParameter().add(newItem); 
     * </pre> 
     * 
     * 
     * <p> 
     * Objects of the following type(s) are allowed in the list 
     * {@link LookupInstances.LookupParameters.LookupParameter } 
     * 
     * 
     */ 
     public List<LookupInstances.LookupParameters.LookupParameter> getLookupParameter() { 
      if (lookupParameter == null) { 
       lookupParameter = new ArrayList<LookupInstances.LookupParameters.LookupParameter>(); 
      } 
      return this.lookupParameter; 
     } 


     /** 
     * <p>Java class for anonymous complex type. 
     * 
     * <p>The following schema fragment specifies the expected content contained within this class. 
     * 
     * <pre> 
     * &lt;complexType> 
     * &lt;simpleContent> 
     *  &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string"> 
     *  &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" /> 
     *  &lt;/extension> 
     * &lt;/simpleContent> 
     * &lt;/complexType> 
     * </pre> 
     * 
     * 
     */ 
     @XmlAccessorType(XmlAccessType.FIELD) 
     @XmlType(name = "", propOrder = { 
      "value" 
     }) 
     public static class LookupParameter { 

      @XmlValue 
      protected String value; 
      @XmlAttribute(name = "name") 
      protected String name; 

      /** 
      * Gets the value of the value property. 
      * 
      * @return 
      *  possible object is 
      *  {@link String } 
      *  
      */ 
      public String getValue() { 
       return value; 
      } 

      /** 
      * Sets the value of the value property. 
      * 
      * @param value 
      *  allowed object is 
      *  {@link String } 
      *  
      */ 
      public void setValue(String value) { 
       this.value = value; 
      } 

      /** 
      * Gets the value of the name property. 
      * 
      * @return 
      *  possible object is 
      *  {@link String } 
      *  
      */ 
      public String getName() { 
       return name; 
      } 

      /** 
      * Sets the value of the name property. 
      * 
      * @param value 
      *  allowed object is 
      *  {@link String } 
      *  
      */ 
      public void setName(String value) { 
       this.name = value; 
      } 

     } 

    } 

} 
17

Ниже приводится некоторая информация, которая должна помочь:

XML

Ниже часть вашего XML. Следует отметить, что атрибут xmlns. Это специальный атрибут и относится к квалификации пространства имен в документе XML.

<lookupInstances xmlns='http://www.pqr.com/awd/rest/v1' name='LKIMGR'> 
    <lookupParameters/> 
</lookupInstances> 

Ниже еще одна версия XML с такой же квалификацией имен:

<abc:lookupInstances xmlns:abc='http://www.pqr.com/awd/rest/v1' name='LKIMGR'> 
    <abc:lookupParameters/> 
</abc:lookupInstances> 

При удалении xmlns атрибут квалификации пространства имен удаляется. Приведенный ниже документ не эквивалентен приведенному выше.

<lookupInstances name='LKIMGR'> 
    <lookupParameters/> 
</lookupInstances> 

Ваша ошибка

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.pqr.com/awd/rest/v1", local:"lookupInstances"). Expected elements are <{}lookupInstances> 

Эта ошибка указывает на то, что вы не сопоставляется квалификации пространства имен правильно.

Картирование Namesapce Квалификационного в JAXB

пространства имен квалификация в JAXB осуществляется с использованием уровня пакета @XmlSchema аннотацию. Аннотации уровня пакета идут в package-info.java. Ниже приведен полный источник этого класса. Если у вас уже есть исходный файл package-info.java, убедитесь, что он скомпилирован и упакован вместе с остальными вашими классами.

@XmlSchema( 
    namespace = "http://www.pqr.com/awd/rest/v1", 
    elementFormDefault = XmlNsForm.QUALIFIED) 
package your_package; 

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

XML Schema

Если вы создаете модель из XML-схемы убедитесь, что эта квалификация имен правильно определить там. Он будет выглядеть так:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    targetNamespace="http://www.pqr.com/awd/rest/v1" 
    xmlns="http://www.pqr.com/awd/rest/v1" 
    elementFormDefault="qualified"> 
</xs:schema> 
+1

Это помогло многим Блейзу. Мне было интересно, как работает приложение, не упоминая квалификацию пространства имен в Java-классе, но, как вы объяснили, это была информация о пакете -info.java, которая имела эту информацию. В моей первой попытке я получил неверный файл xsd, который перетащил меня в неправильный класс Jaxb. Большое спасибо. – Rana

+0

Есть ли способ предоставить URI xmlns из файла свойств? Для меня URI xmlns необходимо динамически изменять для тестовых и производственных сред. – faizi

+0

@XmlSchema (namespace = "http://www.pqr.com/awd/rest/v1", elementFormDefault = XmlNsForm.QUALIFIED) package your_package; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema; Эта часть очень важна для классов, сгенерированных JAXB, особенно 'elementFormDefault = XmlNsForm.QUALIFIED' не будет автоматически добавляться JAXB. Спасибо, Блейз, ваш ответ мне помог. – ClickBright

0

Прежде всего, вы должны проверить входной файл XML. Убедитесь, что входной XML должен иметь один и тот же корневой элемент, как файл XSD (который вы использовали для создания классов JAXB) Поэтому, пожалуйста, попробуйте ниже XML, он будет работать нормально :)

<?xml version='1.0' encoding='UTF-8' standalone='yes'?> 
<lookupInstances name='LKIMGR'> 
<lookupParameters> 
<lookupParameter name='businessArea'>PQAA</lookupParameter> 
<lookupParameter name='MEMBERNUMBER'>ANTHONY1900</lookupParameter> 
</lookupParameters> 
</lookupInstances> 
6

Изменить

@XmlRootElement(name = "lookupInstances") 

в

@XmlRootElement(namespace = "http://www.pqr.com/awd/rest/v1", name = "lookupInstances") 
0
@XmlSchema(namespace = "http://www.pqr.com/awd/rest/v1", 
elementFormDefault = XmlNsForm.QUALIFIED) package your_package; 

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

Эта часть ве для важных классов JAXB, особенно elementFormDefault = XmlNsForm.QUALIFIED, не будет автоматически добавляться JAXB.

Спасибо, Блейз, ваш ответ мне помог.

Смежные вопросы

 Смежные вопросы