java – JAXB和集合中的继承

我如何映射(通过 Java 1.6中的JAXB)集合到XML和XML,在哪里
class mapping{
    @XmlElementWrapper(name="list")
    @XmlElement(name="item")
    Collection<A> list;
}

abstract class A{
}

class B extends A{
    public String onlyB;
}

class C extends A{
    public String onlyC;
}

我想看到这样的XML:

<something> (doesnt matter,I'm using it in another structure)
<list>
<item xsi:type="b"><onlyB>b</onlyB></item>
<item xsi:type="c"><onlyC>c</onlyC></item>
</list>
</something>

它的工作,如果我有

class mapping{        
    @XmlElement(name="item")
    A item;
}

我已经尝试过xmlelementref,但没有成功

我不想使用@XmlElements({@ XmlElement …}),因为正在使用它的其他项目可以添加来自A的派生类

解决方法

您的映射似乎是正确的.您需要确保在创建JAXBContext时包含B和C类.实现此目的的一种方法是使用@XmlSeeAlso.
@XmlSeeAlso(B.class,C.class)
abstract class A{
}

下面是使用xsi:type来表示使用JAXB的域模型中的继承的示例:

> http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html

如果要使用替换组的XML模式概念表示继承,则使用@XmlElementRef:

> http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html

XmlElements对应于XML模式中的选择结构:

> http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html
> http://blog.bdoughan.com/2011/04/xml-schema-to-java-xsd-choice.html

完整的例子

以下是一个完整的例子:

制图

package forum7672121;

import java.util.Collection;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="something")
@XmlAccessorType(XmlAccessType.FIELD)
class Mapping{
    @XmlElementWrapper(name="list")
    @XmlElement(name="item")
    Collection<A> list;
}

一个

package forum7672121;

import javax.xml.bind.annotation.XmlSeeAlso;

@XmlSeeAlso({B.class,C.class})
abstract class A{
}

package forum7672121;

class B extends A{
    public String onlyB;
}

C

package forum7672121;

class C extends A{
    public String onlyC;
}

演示

package forum7672121;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Mapping.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum7672121/input.xml");
        Mapping mapping = (Mapping) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
        marshaller.marshal(mapping,System.out);
    }

}

input.xml中/输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<something>
    <list>
        <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b">
            <onlyB>b</onlyB>
        </item>
        <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="c">
            <onlyC>c</onlyC>
        </item>
    </list>
</something>

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...