我正在使用 EclipseLink MOXy 并且有一个具有相同数据类型的子元素的数据结构。现在我不想序列化具有无限深度的数据结构,而只是第一级。
以下是数据结构的一些示例代码:
package test;
import java.util.Collection;
import java.util.Vector;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlRootElement
public class MyClass {
private int id;
private String details;
private Collection<MyClass> children = new Vector<MyClass>();
public MyClass() {
}
public MyClass(int id, String details) {
this.id = id;
this.details = details;
}
@XmlElementWrapper
@XmlElementRef
public Collection<MyClass> getChildren() {
return children;
}
public void addChild(MyClass child) {
children.add(child);
}
public String getDetails() {
return details;
}
@XmlAttribute
public int getId() {
return id;
}
public void setChildren(Collection<MyClass> children) {
this.children = children;
}
public void setDetails(String details) {
this.details = details;
}
public void setId(int id) {
this.id = id;
}
}
还有我的测试程序:
package test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Test {
public static void main(String[] args) throws Exception {
MyClass l1 = new MyClass(1, "Level 1");
MyClass l2 = new MyClass(2, "Level 2");
l1.addChild(l2);
MyClass l3 = new MyClass(3, "Level 3");
l2.addChild(l3);
JAXBContext jc = JAXBContext.newInstance(MyClass.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(l1, System.out);
}
}
生成以下 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myClass id="1">
<children>
<myClass id="2">
<children>
<myClass id="3">
<children/>
<details>Level 3</details>
</myClass>
</children>
<details>Level 2</details>
</myClass>
</children>
<details>Level 1</details>
</myClass>
但是,我也希望 xml 看起来像:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myClass id="1">
<children>
<myClass id="2">
<details>Level 2</details>
</myClass>
</children>
<details>Level 1</details>
</myClass>
谢谢。