gpt4 book ai didi

java - JAXB 解码 @XmlAnyElement

转载 作者:行者123 更新时间:2023-12-02 03:32:51 27 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" Listcom.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 {

}

演示代码

input.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/56875093/

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