Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> JAXB xml => java troubles 
:(
    Опции темы
Slanix
Дата 1.8.2008, 09:12 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 158
Регистрация: 30.1.2004

Репутация: нет
Всего: 1



Помогите разобраться.
Есть такой xsd
Код

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified" attributeFormDefault="unqualified"
           xmlns:ns="http://www.iam.ru/ns"
           targetNamespace="http://www.iam.ru/ns">
    <xs:element name="Message">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Request">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="MyRequest" type="ns:MyRequest">
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
            <xs:attribute name="Sender" use="required" type="xs:string"/>
            <xs:attribute name="Receiver" use="required" type="xs:string"/>
            <xs:attribute name="DateSend" use="required" type="xs:string"/>
        </xs:complexType>
    </xs:element>
    <xs:complexType name="Info">
        <xs:sequence>
     <xs:element name="El1" type="xs:decimal">
     </xs:element>
     <xs:element name="El2" type="xs:string">
     </xs:element>
       </xs:sequence>
    </xs:complexType>
    <xs:complexType name="MyRequest">
     <xs:sequence>
         <xs:element name="Info" type="ns:Info">
         </xs:element>
     </xs:sequence>
    </xs:complexType>
</xs:schema>


По этой XSD генерятся классы и XML.

Код

<?xml version="1.0" encoding="UTF-8"?>
<ns:Message DateSend="" Receiver="" Sender=""
                      xmlns:ns="http://www.iam.ru/ns" 
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <ns:Request>
    <ns:MyRequest>
      <ns:Info>
        <ns:El1>0.0</ns:El1>
        <ns:El2>Test</ns:El2>
      </ns:Info>
    </ns:MyRequest>
  </ns:Request>
</ns:Message>


При попытке преобразовать этот XML в Java objects
получаю ошибку: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ns:Message'.

--------------------
Я буду искать лица Твоего, Господи Пс.26:8
PM MAIL ICQ YIM   Вверх
SoulKeeper
Дата 1.8.2008, 09:37 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 375
Регистрация: 14.1.2007
Где: Ukraine, Lviv.

Репутация: нет
Всего: 15



Код

package jaxbdemo;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;

public class Main {

    public static void main(String[] args) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller u = jaxbContext.createUnmarshaller();
        Message m = (Message) u.unmarshal(new File("demo.xml"));
        System.out.println(m.getRequest().getMyRequest().getInfo().getEl2());
    }
}


Код

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-325 
// 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: 2008.08.01 at 09:26:44 AM EEST 
//


package jaxbdemo;

import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


/**
 * <p>Java class for Info complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="Info">
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="El1" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
 *         &lt;element name="El2" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Info", namespace = "http://www.iam.ru/ns", propOrder = {
    "el1",
    "el2"
})
public class Info {

    @XmlElement(name = "El1", namespace = "http://www.iam.ru/ns", required = true)
    protected BigDecimal el1;
    @XmlElement(name = "El2", namespace = "http://www.iam.ru/ns", required = true)
    protected String el2;

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

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

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

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

}



Код

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-325 
// 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: 2008.08.01 at 09:26:44 AM EEST 
//


package jaxbdemo;

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="Request">
 *           &lt;complexType>
 *             &lt;complexContent>
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 &lt;sequence>
 *                   &lt;element name="MyRequest" type="{http://www.iam.ru/ns}MyRequest"/>
 *                 &lt;/sequence>
 *               &lt;/restriction>
 *             &lt;/complexContent>
 *           &lt;/complexType>
 *         &lt;/element>
 *       &lt;/sequence>
 *       &lt;attribute name="Sender" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       &lt;attribute name="Receiver" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       &lt;attribute name="DateSend" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "request"
})
@XmlRootElement(name = "Message", namespace = "http://www.iam.ru/ns")
public class Message {

    @XmlElement(name = "Request", namespace = "http://www.iam.ru/ns", required = true)
    protected Message.Request request;
    @XmlAttribute(name = "Sender", required = true)
    protected String sender;
    @XmlAttribute(name = "Receiver", required = true)
    protected String receiver;
    @XmlAttribute(name = "DateSend", required = true)
    protected String dateSend;

    /**
     * Gets the value of the request property.
     * 
     * @return
     *     possible object is
     *     {@link Message.Request }
     *     
     */
    public Message.Request getRequest() {
        return request;
    }

    /**
     * Sets the value of the request property.
     * 
     * @param value
     *     allowed object is
     *     {@link Message.Request }
     *     
     */
    public void setRequest(Message.Request value) {
        this.request = value;
    }

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

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

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

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

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

    /**
     * Sets the value of the dateSend property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setDateSend(String value) {
        this.dateSend = 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="MyRequest" type="{http://www.iam.ru/ns}MyRequest"/>
     *       &lt;/sequence>
     *     &lt;/restriction>
     *   &lt;/complexContent>
     * &lt;/complexType>
     * </pre>
     * 
     * 
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "myRequest"
    })
    public static class Request {

        @XmlElement(name = "MyRequest", namespace = "http://www.iam.ru/ns", required = true)
        protected MyRequest myRequest;

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

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

    }

}



Код

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-325 
// 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: 2008.08.01 at 09:26:44 AM EEST 
//


package jaxbdemo;

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


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

    @XmlElement(name = "Info", namespace = "http://www.iam.ru/ns", required = true)
    protected Info info;

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

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

}




Код

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-325 
// 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: 2008.08.01 at 09:26:44 AM EEST 
//


package jaxbdemo;

import javax.xml.bind.annotation.XmlRegistry;


/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the jaxbdemo package. 
 * <p>An ObjectFactory allows you to programatically 
 * construct new instances of the Java representation 
 * for XML content. The Java representation of XML 
 * content can consist of schema derived interfaces 
 * and classes representing the binding of schema 
 * type definitions, element declarations and model 
 * groups.  Factory methods for each of these are 
 * provided in this class.
 * 
 */
@XmlRegistry
public class ObjectFactory {


    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: jaxbdemo
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link Message.Request }
     * 
     */
    public Message.Request createMessageRequest() {
        return new Message.Request();
    }

    /**
     * Create an instance of {@link Info }
     * 
     */
    public Info createInfo() {
        return new Info();
    }

    /**
     * Create an instance of {@link MyRequest }
     * 
     */
    public MyRequest createMyRequest() {
        return new MyRequest();
    }

    /**
     * Create an instance of {@link Message }
     * 
     */
    public Message createMessage() {
        return new Message();
    }

}



Это сообщение отредактировал(а) SoulKeeper - 1.8.2008, 09:54
PM MAIL   Вверх
Slanix
Дата 1.8.2008, 10:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 158
Регистрация: 30.1.2004

Репутация: нет
Всего: 1



Да, всё так, только я добавляю валидацию
Код

 u.setSchema(getSchema("MySchema.xsd"));

И в этом случае появляется ошибка.

Хотя нет, не появляется.
В общем буду разбираться, ошибка появляется когда начинаю работать на ESB и XML кладётся в очередь.

Это сообщение отредактировал(а) Slanix - 1.8.2008, 12:30
--------------------
Я буду искать лица Твоего, Господи Пс.26:8
PM MAIL ICQ YIM   Вверх
Slanix
Дата 1.8.2008, 13:41 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 158
Регистрация: 30.1.2004

Репутация: нет
Всего: 1



Такая ошибка если отключить валидацию:
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"ns:Message"). Expected elements are <{http://www.iam.ru/ns}Message>

--------------------
Я буду искать лица Твоего, Господи Пс.26:8
PM MAIL ICQ YIM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java EE (J2EE) и Spring | Следующая тема »


 




[ Время генерации скрипта: 0.0795 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.