首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JaxB UNMarshalling问题

JaxB UNMarshalling问题
EN

Stack Overflow用户
提问于 2010-11-28 11:48:53
回答 1查看 968关注 0票数 2

我试图在以下线程中运行相同的示例:

JAXB Annotations - Mapping interfaces and @XmlElementWrapper

但我收到以下例外情况:

意外元素(uri:"",本地:“狗”)。期望元素是<{奇怪的问号符号}>catchAll>

..。

知道我为什么会有这个例外吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-01 11:01:25

我成功地运行了这个示例,但是在将XmlElements标记与java.uill.List一起使用之后,下面的代码如下:

@XmlRootElement class Zoo {

代码语言:javascript
复制
@XmlElements({
        @XmlElement(name = "Dog" , type = Dog.class),
        @XmlElement(name = "Cat" , type = Cat.class)
})
private List<Animal> animals;

public static void main(String[] args) throws Exception {
    Zoo zoo = new Zoo();
    zoo.animals = new ArrayList<Animal>();

    Dog doggy = new Dog();
    doggy.setDogProp("Doggy");

    Cat catty = new Cat();
    catty.setCatProp("Catty");

    zoo.animals.add(doggy);
    zoo.animals.add(catty);

    JAXBContext jc = JAXBContext.newInstance(Zoo.class, Dog.class, Cat.class);
    Marshaller marshaller = jc.createMarshaller();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    marshaller.marshal(zoo, os);

    System.out.println(os.toString());

    Unmarshaller unmarshaller = jc.createUnmarshaller();

    unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());

    Zoo unmarshalledZoo = (Zoo) unmarshaller.unmarshal(new ByteArrayInputStream(os.toByteArray()));

    if (unmarshalledZoo.animals == null) {
        System.out.println("animals was null");
    } else if (unmarshalledZoo.animals.size() == 2) {
        System.out.println("it worked");
    } else {
        System.out.println("failed!");
    }
}

public interface Animal {
}

@XmlRootElement
public static class Dog implements Animal {

    private String dogProp;

    public String getDogProp() {
        return dogProp;
    }

    public void setDogProp(String dogProp) {
        this.dogProp = dogProp;
    }
}

@XmlRootElement
public static class Cat implements Animal {

    private String catProp;

    public String getCatProp() {
        return catProp;
    }

    public void setCatProp(String catProp) {
        this.catProp = catProp;
    }
}

}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4296588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档