gpt4 book ai didi

java - JAXB 解码 @XmlAnyElement

转载 作者:搜寻专家 更新时间:2023-10-31 20:02:57 26 4
gpt4 key购买 nike

我创建了三个 JAXB 类:Home , Person , Animal . Java类首页有变List<Object> any可能包含 Person 和/或 Animal 实例。

    public class Home {
@XmlAnyElement(lax = true)
protected List<Object> any;
//setter getter also implemented
}
@XmlRootElement(name = "Person") // Edited
public class Person {
protected String name; //setter getter also implemented
}
@XmlRootElement(name = "Animal") // Edited
public class Animal {
protected String name; //setter getter also implemented
}

/* 解码后 */

 Home home ;

for(Object obj : home .getAny()){
if(obj instanceof Person ){
Person person = (Person )obj;
// .........
}else if(obj instanceof Animal ){
Animal animal = (Animal )obj;
// .........
}
}

我需要实现 Person or Animal对象保存在 "Home.any" List可变但 "Home.any" List 的内容是 com.sun.org.apache.xerces.internal.dom.ElementNSImpl 的实例而不是 Animal or Person .

那么有没有办法实现Animal or Person "Home.any" List 中保存在 xml 中的实例.

最佳答案

您需要在您希望在用 @XmlAnyElement(lax=true) 注释的字段/属性中显示为实例的类上添加 @XmlRootElement

Java 模型

首页

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Home {
@XmlAnyElement(lax = true)
protected List<Object> any;

//setter getter also implemented
}

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Person")
public class Person {

动物

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Animal")
public class Animal {

}

演示代码

输入.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<Person/>
<Animal/>
<Person/>
</root>

演示

import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Home.class, Person.class, Animal.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource("src/forum20329510/input.xml");
Home home = unmarshaller.unmarshal(xml, Home.class).getValue();

for(Object object : home.any) {
System.out.println(object.getClass());
}
}

}

输出

class forum20329510.Person
class forum20329510.Animal
class forum20329510.Person

更多信息

关于java - JAXB 解码 @XmlAnyElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20329510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com