javax.XML.unir.UnmarshalException: elemento inesperado (uri:"", Grupo local:"")


unexpected element (uri:"", local:"Group"). Expected elements are <{}group>

Cumple una excepción al desmarcar desde xml

JAXBContext jc = JAXBContext.newInstance(Group.class); 
Unmarshaller unmarshaller = jc.createUnmarshaller();
Group group = (User)unmarshaller.unmarshal(new File("group.xml"));

La clase de grupo no tiene ninguna anotación y grupo.xml solo contiene datos.

Cualquier cosa puede ser la causa?

Author: Aaron Kurtzhals, 2011-03-05

9 answers

Parece que su documento XML tiene el elemento raíz "Group" en lugar de "group". Usted puede:

  1. Cambia el elemento raíz de tu XML para que sea "group"
  2. Agregue la anotación @XmlRootElement(name="Group") a las clases Group.
 92
Author: Blaise Doughan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-05 11:04:48

Necesitas poner package-info.java en su paquete jaxb generado. Su contenido debería ser algo así

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.org/StudentOperations/")
package generated.marsh;
 28
Author: Ahmed Azraq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-29 16:02:40

Afortunadamente, la clase package-info no es necesaria. Pude solucionar mi problema con la solución iowatiger08.

Aquí está mi corrección que muestra el mensaje de error para ayudar a unir los puntos para algunos.

Mensaje de error

[2] Javax.XML.unir.UnmarshalException: elemento inesperado (uri: " http://global.aon.bz/schema/cbs/archive/errorresource/0 ", local: "errorresource"). Los elementos esperados son

Código antes de fix

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="", propOrder={"error"})
@XmlRootElement(name="errorresource")
public class Errorresource

Código después de fix

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="", propOrder={"error"})
@XmlRootElement(name="errorresource", namespace="http://global.aon.bz/schema/cbs/archive/errorresource/0")
public class Errorresource

Puede ver el espacio de nombres agregado a @XmlRootElement como se indica en el mensaje de error.

 15
Author: Glenn Mason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-28 05:18:32

Después de buscar más, el elemento raíz tiene que estar asociado con un espacio de nombres de esquema como Blaise está señalando. Sin embargo, no tenía un paquete de información java. Así que sin usar la anotación @XMLSchema, pude corregir este problema usando

@XmlRootElement (name="RetrieveMultipleSetsResponse", namespace = XMLCodeTable.NS1)
@XmlType(name = "ns0", namespace = XMLCodeTable.NS1)
@XmlAccessorType(XmlAccessType.NONE)
public class RetrieveMultipleSetsResponse {//...}

Espero que esto ayude!

 7
Author: iowatiger08,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-12 22:05:38

Esta es una solución para un caso de uso bastante nicho, pero me llega cada vez. Si está utilizando el generador Eclipse Jaxb, crea un archivo llamado package-info.

@javax.xml.bind.annotation.XmlSchema(namespace = "blah.xxx.com/em/feed/v2/CommonFeed")
package xxx.blah.mh.domain.pl3xx.startstop;

Si elimina este archivo, permitirá analizar un xml más genérico. ¡Inténtalo!

 2
Author: markthegrea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-11 16:07:10

Yo tenía el mismo problema.. Me ayudó, estoy especificar los mismos nombres de campo de mis clases como los nombres de etiqueta en el archivo xml (el archivo viene de un sistema externo).

Por ejemplo:

Mi archivo xml:

<Response>
  <ESList>
     <Item>
        <ID>1</ID>
        <Name>Some name 1</Name>
        <Code>Some code</Code>
        <Url>Some Url</Url>
        <RegionList>
           <Item>
              <ID>2</ID>
              <Name>Some name 2</Name>
           </Item>
        </RegionList>
     </Item>
  </ESList>
</Response>

Mi clase de respuesta:

@XmlRootElement(name="Response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {
    @XmlElement
    private ESList[] ESList = new ESList[1]; // as the tag name in the xml file..

    // getter and setter here
}

Mi clase ESList:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ESList")
public class ESList {
    @XmlElement
    private Item[] Item = new Item[1]; // as the tag name in the xml file..

    // getters and setters here
}

Mi clase de artículo:

@XmlRootElement(name="Item")
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
    @XmlElement
    private String ID; // as the tag name in the xml file..
    @XmlElement
    private String Name; // and so on...
    @XmlElement
    private String Code;
    @XmlElement
    private String Url;
    @XmlElement
    private RegionList[] RegionList = new RegionList[1];

    // getters and setters here
}

Mi clase RegionList:

@XmlRootElement(name="RegionList")
@XmlAccessorType(XmlAccessType.FIELD)
public class RegionList {
    Item[] Item = new Item[1];

    // getters and setters here
}

Mi clase de DemoUnmarshalling:

public class DemoUnmarshalling {
    public static void main(String[] args) {
        try {
            File file = new File("...");

            JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            jaxbUnmarshaller.setEventHandler(
                new ValidationEventHandler() {
                    public boolean handleEvent(ValidationEvent event ) {
                        throw new RuntimeException(event.getMessage(),
                            event.getLinkedException());
                    }
                }
            );

            Response response = (Response) jaxbUnmarshaller.unmarshal(file);

            ESList[] esList = response.getESList();
            Item[] item = esList[0].getItem();
            RegionList[] regionLists = item[0].getRegionList();
            Item[] regionListItem = regionLists[0].getItem();

            System.out.println(item[0].getID());
            System.out.println(item[0].getName());
            System.out.println(item[0].getCode());
            System.out.println(item[0].getUrl());
            System.out.println(regionListItem[0].getID());
            System.out.println(regionListItem[0].getName());

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

Da:

1
Some name 1
Some code
Some Url
2
Some name 2
 1
Author: Aleksey Bykov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-21 11:57:55

Lo mismo para mí. El nombre de la clase de asignación era Mbean pero el nombre raíz de la etiqueta era {[2] } así que tuve que agregar la anotación:

@XmlRootElement(name="mbean")
public class MBean { ... }
 0
Author: Laura Liparulo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-21 11:21:16

Si nada de lo anterior funciona, intente agregar

@XmlRootElement(name="Group") a las clases grupales.

 0
Author: F.O.O,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-14 17:37:30

Tuve el mismo problema. He añadido los siguientes atributos a <xs:schema..> elementFormDefault=" qualified " attributeFormDefault = "unqualified"

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://www.example.com/schemas/ArrayOfMarketWithStations"
    targetNamespace="http://www.example.com/schemas/ArrayOfMarketWithStations" 
    elementFormDefault="qualified" attributeFormDefault="unqualified" >

Y las clases java re-generadas ejecutando xjc, que corrigió package-info.Java.

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.com/schemas/ArrayOfMarketWithStations", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)

Esto solucionó el problema para mí.

 0
Author: Rashmi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 14:54:59