我试图弄清楚是否可以将一个 xml 元素解码到多个 pojo。例如:
对于 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;
}
元素尺寸
你正常注释这个类。在您的示例中,您注释了属性,但仅提供了 setter/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 解码以增加 pojo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5779555/