gra*_*ntk 5 java jaxb unmarshalling
我试图找出是否有可能将xml元素解组到多个pojo。例如:
对于xml:
<type>
<id>1</id>
<cost>12</cost>
<height>15</height>
<width>13</width>
<depth>77</depth>
</type>
Run Code Online (Sandbox Code Playgroud)
物品类别
@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
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用Netbeans 6.9生成的许多JAXB映射和许多测试类来完成类似的工作,但是现在已经掌握了。有谁知道这是否可以在没有任何中间对象的情况下完成?
您可以使用EclipseLink JAXB (MOXy)中的 @XmlPath 扩展来完成此用例(我是 MOXy 技术负责人):
根
JAXB 需要单个对象来解组,我们将引入一个类来履行此角色。该类将具有与您希望解组的两个对象相对应的字段,并用 self 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;
}
Run Code Online (Sandbox Code Playgroud)
物品尺寸
您通常会注释此类。在您的示例中,您注释了属性,但仅提供了 getter。这将导致 JAXB 认为这些是只写映射。
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class ItemDimensions {
private Integer height;
private Integer width;
private Integer depth;
}
Run Code Online (Sandbox Code Playgroud)
物品
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
private Integer id;
private Double cost;
}
Run Code Online (Sandbox Code Playgroud)
演示
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);
}
}
Run Code Online (Sandbox Code Playgroud)
jaxb.属性
要使用 MOXy 作为 JAXB 实现,您必须在域对象中提供名为 jaxb.properties 的文件,其中包含以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2712 次 |
| 最近记录: |