JAXB / MOXy - 在单个类中解组子级和嵌套子级的值,包括对具有相同名称的元素的支持

时间:2014-07-10 19:36:58

标签: jaxb unmarshalling moxy

我想将具有相同名称的嵌套子项的xml文件解组为单个类。我尝试了所有我发现但没有任何效果的东西,嵌套子元素的值保持为空。

有什么问题?

jaxb.properties

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

myfile.xml中

<?xml version="1.0" encoding="UTF-8"?>
<clock>
  <name>myClock</name>
  <times>
    <starttime>09:00</starttime>
    <endtime>12:00</endtime>
    <starttime>13:00</starttime>
    <endtime>17:00</endtime>
  </times>
</clock>

Clock.java

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Clock {

    @XmlElement
    private String name;

    @XmlPath("times/starttime[1]/text()")
    private String amStartTime;

    @XmlPath("times/endtime[1]/text()")
    private String amEndTime;

    @XmlPath("times/starttime[2]/text()")
    private String pmStartTime;

    @XmlPath("times/endtime[2]/text()")
    private String pmEndTime;

}

测试代码

File file = new File("myFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Clock.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Clock clock = (Clock) jaxbUnmarshaller.unmarshal(file);

Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(clock, System.out);

输出继电器

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<clock>
    <name>myClock</name>
</clock>

1 个答案:

答案 0 :(得分:1)

此处找到2个解决方案:JAXBContext, jaxb.properties and moxy

我可以将jaxb.properties放在Clock.java的包中,也可以这样获取我的JABXContext实例:

JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {Clock.class}, null);