注意:我是EclipseLink JAXB (MOXy) 领导,也是JAXB 2 (JSR-222) 专家组的成员。
假设您的 XML 文档如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<row>
<col1>a1</col1>
<col2>b1</col2>
<col3>c1</col3>
</row>
<row>
<col1>a1</col1>
<col2>b2</col2>
<col3>c2</col3>
</row>
</rows>
您可以利用 MOXy 的 @XmlPath 注释并执行类似的操作。 EclipseLink 还包括一个JPA implementation:
行
您需要创建一个 Root 对象来保存所有内容:
package forum8577359;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Rows {
@XmlElement(name="row")
private List<A> rows;
}
一个
由于A、B 和C 对象的内容都在同一级别,您可以使用MOXy 的@XmlPath 注释并指定"." XPath。这告诉 MOXy 对象和它所引用的对象出现在同一级别:
package forum8577359;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
private String col1;
@XmlPath(".")
private B b;
}
B
我们再次使用@XmlPath(".") 来映射B 和C 之间的关系:
package forum8577359;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlAccessorType(XmlAccessType.FIELD)
public class B {
private String col2;
@XmlPath(".")
private C c;
}
C
package forum8577359;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class C {
private String col3;
}
演示
以下演示代码可用于运行此示例:
package forum8577359;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Rows.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum8577359/input.xml");
Rows rows = (Rows) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rows, System.out);
}
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要在与您的域类相同的包中包含一个 jaxb.properties 文件,并带有以下条目:
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
更多信息