UnmarshalException: неожиданный элемент (uri: "http://www.namespace.com/RTS", local: "container") - PullRequest
0 голосов
/ 06 апреля 2020

Я пытаюсь сопоставить свои xml с java классами. Xml поступает от стороннего сервиса. Структура такая же, но может быть другой префикс или пространство имен. XML:

<?xml version="1.0" encoding="UTF-8"?>
<xdms:container xmlns:xdms="http://www.namespace.com/RTS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xdms:uid="FHGHDFGDFJKGDFHG" xdms:version="3.2">
    <xdms:requisites>
        <xdms:documentKind>letter</xdms:documentKind>
        <xdms:classification>main</xdms:classification>
        <xdms:annotation>unknown</xdms:annotation>
    </xdms:requisites>
</>

Мои классы:

@XmlRootElement(name = "container")
@XmlAccessorType(XmlAccessType.FIELD)
public class Container {
    private static final long serialVersionUID = 1L;

    @XmlElement(name = "requisites")
    private Requisites requisites;

    public Container() {
        super();
    }

    @Override
    public String toString() {
        return "Container{" +
                "requisites=" + requisites +
                '}';
    }
}

@XmlRootElement(name = "requisites")
@XmlAccessorType(XmlAccessType.FIELD)
public class Requisites implements Serializable {
    private static final long serialVersionUID = 1L;

    private String documentKind;
    private String classification;
    private String annotation;

    public Requisites() {
        super();
    }

    @Override
    public String toString() {
        return "Requisites{" +
                "documentKind='" + documentKind + '\'' +
                ", classfication='" + classification + '\'' +
                ", annotation='" + annotation + '\'' +
                '}';
    }
}

и основной класс, в котором я выполняю анализ:

    JAXBContext jaxbContext;
    File xmlFile = new File("test.xml");
    try
    {
        jaxbContext = JAXBContext.newInstance(Container.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Container cont = (Container) jaxbUnmarshaller.unmarshal(xmlFile);

        System.out.println(cont);
    }
    catch (JAXBException e)
    {
        e.printStackTrace();
    }

И я получаю ошибку:

javax. xml .bind.UnmarshalException: непредвиденный элемент (uri: "http://www.namespace.com/RTS", local: "container"). Ожидаемые элементы: <{} container>, <{} Requisites> на com.sun. xml .internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent (UnmarshallingContext. java: 726) на com.sun. xml .internal.bind.v2.runtime.unmarshaller.Loader.reportError (Loader. java: 247) на com.sun. xml .internal.bind.v2.runtime.unmarshaller.Loader.reportError (Loader . java: 242) в com.sun. xml .internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement (Loader. java: 109) в com.sun. xml .internal.bind .v2.runtime.unmarshaller.UnmarshallingContext $ DefaultRootLoader.childElement (UnmarshallingContext. java: 1131) в com.sun. xml .internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.ht. 556) в com.sun. xml .internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement (UnmarshallingContext. java: 538) в com.sun. xml .internal.bind.v2.runtime. unmarshaller.SAXConnector.startElement (SAXConnector. java: 153) на com.sun.org. apache .xerces.int ernal.parsers. org. apache .xerces.internal.impl.XMLNSDocumentScannerImpl $ NSContentDriver.scanRootElementHook (XMLNSDocumentScannerImpl. java: 613) в com.sun.org. apache .xnerces.internal.impmentImpraDrampFrampFDF . java: 3132) на com.sun.org. apache .xerces.internal.impl.XMLDocumentScannerImpl $ PrologDriver.next (XMLDocumentScannerImpl. java: 852)

UPD: Я добавил nameSpace, ошибка ушла. Но поля моих объектов не заполнены информацией. Они пусты, хотя в xml они заполнены информацией

Контейнер {Requisites = Requisites {documentKind = 'null', classfication = 'null', annotation = 'null'}}

Ответы [ 2 ]

1 голос
/ 06 апреля 2020

Используйте атрибут пространства имен в @XmlRootElement следующим образом:

@XmlRootElement(name="container", namespace="http://www.namespace.com/RTS")

В случае, если он по-прежнему выдает ту же ошибку, вы также должны указать атрибут пространства имен в своем @XmlElement:

@XmlElement(name="requisites", namespace="http://www.namespace.com/RTS")

Каждый ваш атрибут внутри тега Requisites также должен содержать пространство имен в аннотации @XmlElement.

1 голос
/ 06 апреля 2020

Вы не указываете пространство имен в своем классе jaxb

Что-то вроде этого:

@XmlRootElement(name = "container", namespace = "http://www.namespace.com/RTS")
@XmlAccessorType(XmlAccessType.FIELD)
public class Container {

    @XmlElement(name = "requisites", namespace="http://www.namespace.com/RTS")
    private Requisites requisites;

}

вам может понадобиться добавить пространство имен к каждому элементу в Requisites.

@XmlRootElement(name = "requisites")
@XmlAccessorType(XmlAccessType.FIELD)
public class Requisites implements Serializable {
    private static final long serialVersionUID = 1L;

    @XmlElement(name = "documentKind", namespace="http://www.namespace.com/RTS")
    private String documentKind;
    @XmlElement(name = "classification", namespace="http://www.namespace.com/RTS")
    private String classification;
    @XmlElement(name = "annotation", namespace="http://www.namespace.com/RTS")
    private String annotation;
...