【问题标题】:Parsing class hierarchy using JaxB使用 JaxB 解析类层次结构
【发布时间】:2013-03-18 13:40:53
【问题描述】:

我有类层次结构

interface Intf {}

Class A implements Intf{}

Class B implements Intf{}

现在我使用上面的Class AClass B 用JaxB 的elp 读取两个不同的XML 文件。谁能建议我如何在 JaxB 中配置和使用上述结构?

【问题讨论】:

  • 您能提供一些额外的信息吗?就问题而言,界面没有考虑在内,因为它将被忽略。
  • 另外,您打算使用哪个 JAXB 提供程序? F.e. Jackson 支持 JAXB annotations 并具有良好的多态类型处理能力,并且它是大量技术的典型 JAXB 提供者:CXF、RestEasy 等。
  • @n1ckolas - Jackson 不是 JAXB (JSR-222) 提供者。虽然一些 JAX-RS 实现使用 Jackson 作为其 JSON 绑定的方法,但我不知道有任何将它用于 XML 绑定。
  • 我不是说它是默认,我是说它是典型,即非常普遍,因为它非常快速且可自定义.特别是它对多态类型有很好的支持。 F.e.我个人将 Jackson 用于 JSON 和 XML REST-API,具有相同的注释集并重用相同的 JAX-RS 服务(Apache CXF)。

标签: java xml-parsing jaxb


【解决方案1】:

对于您的用例,接口不考虑在内。如果您想将 AB 映射到不同的 XML 结构,您可以继续这样做,我将在下面通过示例进行演示。

JAVA 模型

IntF

public interface IntF {

    public String getFoo();

    public void setFoo(String foo);

}

一个

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

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;
    }

}

演示代码

演示

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);
    }

}

输出

<?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"/>

【讨论】:

  • 嗨 Blaise,在CLass A 我有其他类说 SubA 并且在这个类中有属性。在Class B 的情况下也是如此。这个配置我不能按照你的建议去做。不然怎么办?
  • @Navnath - 您能否编辑您的问题以包含模型的简化版本?
  • 我已经扩展了这个问题here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2014-09-28
相关资源
最近更新 更多