栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

是否可以以编程方式配置JAXB?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

是否可以以编程方式配置JAXB?

您可以创建如下的通用

Wrapper
对象:

包装纸

您可以创建一个通用包装器类,其

List
属性带有注释
@XmlAnyElement(lax=true)
。用于填充此列表的对象的类型将基于其根元素

package forum13272288;import java.util.*;import javax.xml.bind.annotation.XmlAnyElement;public class Wrapper<T> {    private List<T> items = new ArrayList<T>();    @XmlAnyElement(lax=true)    public List<T> getItems() {        return items;    }}

地址

您将需要用注释列表的可能内容

@XmlRootElement

package forum13272288;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Address {}

Person

package forum13272288;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Person {}

演示版

下面的演示代码演示了如何使用

Wrapper
该类。由于根元素可以不同,因此您需要指定要解组包装类。或者,您可以利用
@XmlElementDecl
注释将多个根元素与包装类相关联

package forum13272288;import javax.xml.bind.*;import javax.xml.transform.stream.StreamSource;public class Demo {    public static void main(String[] args) throws Exception {        JAXBContext jc = JAXBContext.newInstance(Wrapper.class, Person.class, Address.class);        Unmarshaller unmarshaller = jc.createUnmarshaller();        Marshaller marshaller = jc.createMarshaller();        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        StreamSource personsXML = new StreamSource("src/forum13272288/persons.xml");        JAXBElement<Wrapper> wrapper1 = unmarshaller.unmarshal(personsXML, Wrapper.class);        marshaller.marshal(wrapper1, System.out);        StreamSource addressesXML = new StreamSource("src/forum13272288/addresses.xml");        JAXBElement<Wrapper> wrapper2 = unmarshaller.unmarshal(addressesXML, Wrapper.class);        marshaller.marshal(wrapper2, System.out);    }}

输出量

以下是运行演示代码的输出。文件

persons.xml
addresses.xml
看起来就像那里相应的输出。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><persons>    <person/>    <person/></persons><?xml version="1.0" encoding="UTF-8" standalone="yes"?><addresses>    <address/>    <address/></addresses>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号