使用JaxB解析类层次结构 [英] Parsing class hierarchy using JaxB

查看:97
本文介绍了使用JaxB解析类层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类层次结构

interface Intf {}

Class A implements Intf{}

Class B implements Intf{}

现在我在<$ c以上使用$ c> A类和 B类用jpB的elp读取两个不同的XML文件。任何人都可以建议我如何配置和使用JaxB中的上述结构?

Now I am using above Class A and Class B to read two diffrent XML files with the elp of JaxB. Can any one suggest me how to configure and use structure like above in JaxB?

推荐答案

对于您的用例,界面不如果你想将 A B 映射到不同的XML结构,你可以继续这样做,我下面将举例说明。

For your use case the interface doesn't factor in. If you want to map A and B to different XML structures you can go ahead and do so, I'll demonstrate below with an example.

JAVA模型

IntF

IntF

public interface IntF {

    public String getFoo();

    public void setFoo(String foo);

}

A

A

import javax.xml.bind.annotation.*;

@XmlRootElement
public class A implements IntF {

    private String foo;

    @Override
    @XmlElement(name="renamed-foo")
    public String getFoo() {
        return foo;
    }

    @Override
    public void setFoo(String foo) {
        this.foo = foo;
    }

}

B

B

import javax.xml.bind.annotation.*;

@XmlRootElement
public class B implements IntF {

    private String foo;

    @Override
    @XmlAttribute
    public String getFoo() {
        return foo;
    }

    @Override
    public void setFoo(String foo) {
        this.foo = foo;
    }

}

DEMO CODE

演示

Demo

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class, B.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        A a = new A();
        a.setFoo("Hello World");
        marshaller.marshal(a, System.out);

        B b = new B();
        b.setFoo("Hello World");
        marshaller.marshal(b, System.out);
    }

}

输出

Output

<?xml version="1.0" encoding="UTF-8"?>
<a>
    <renamed-foo>Hello World</renamed-foo>
</a>
<?xml version="1.0" encoding="UTF-8"?>
<b foo="Hello World"/>

这篇关于使用JaxB解析类层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆