编程语言
首页 > 编程语言> > java – JAXB unmarshall到多个pojo的

java – JAXB unmarshall到多个pojo的

作者:互联网

我试图弄清楚是否有可能将xml元素解组为多个pojos.例如:

对于xml:

<type>
  <id>1</id>
  <cost>12</cost>
  <height>15</height>
  <width>13</width>
  <depth>77</depth>
</type>

物品类

@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlRootElement(name="type")
public class Item {
  private Integer id;
  private Double cost;

  @XmlElement(name="id")
  public Integer getId(){
    return id;
  }

  @XmlElement(name="cost")
  public Double getCost(){
    return cost
  }
}

ItemDimensions类

@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlRootElement(name="type")
public class ItemDimensions {
  private Integer height;
  private Integer width;
  private Integer depth;

  @XmlElement(name="height")
  public Integer getHeight(){
    return height;
  }

  @XmlElement(name="width")
  public Integer getWidth(){
    return width;
  }

  @XmlElement(name="depth")
  public Integer getDepth(){
    return depth;
  }
}

我尝试使用Netbeans 6.9和许多测试类生成的大量JAXB映射来完成类似的操作,但现在已经得到了.有谁知道这是否可以在没有任何中间对象的情况下完成?

解决方法:

您可以使用EclipseLink JAXB (MOXy)中的@XmlPath扩展来完成此用例(我是MOXy技术主管):

JAXB需要单个对象来解组,我们将引入一个类来实现这个角色.此类将包含与要使用自我XPath注释的两个对象相对应的字段:@XmlPath(“.”)

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="type")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlPath(".")
    private Item item;

    @XmlPath(".")
    private ItemDimensions itemDimensions;

}

ItemDimensions

你通常会注释这个类.在您的示例中,您可以注释属性,但仅提供getter.这将导致JAXB认为那些是只写映射.

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class ItemDimensions {

    private Integer height;
    private Integer width;
    private Integer depth;

}

项目

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Item {

    private Integer id;
    private Double cost;

}

演示

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        Unmarshaller u = jc.createUnmarshaller();
        Object o = u.unmarshal(new File("input.xml"));

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

}

jaxb.properties

要将MOXy用作JAXB实现,必须使用以下条目为域对象提供名为jaxb.properties的文件:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

标签:java,jaxb,unmarshalling
来源: https://codeday.me/bug/20190704/1381328.html