您可以使用带有JAXB (JSR-222)注释的 Java 模型来支持您的用例。可以多次出现的元素将对应List
于 Java 模型中的属性。以下是如何映射文档的示例。
桌子
我们将使用@XmlElementWrapper
注解添加分组元素,并使用@XmlElement
注解设置集合中项目的元素名称。
package forum11543081;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="root-element")
@XmlAccessorType(XmlAccessType.FIELD)
public class Table {
@XmlElementWrapper(name="table")
@XmlElement(name="row")
private List<Row> rows;
}
排
如果您的属性/字段的名称与生成的 XML 元素的名称相匹配,那么您不需要任何注释。
package forum11543081;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Row {
private List<String> d;
}
演示
下面是一个证明映射有效的独立示例:
package forum11543081;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Table.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11543081/input.xml");
Table table = (Table) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(table, System.out);
}
}
输入.xml/输出
<root-element>
<table>
<row>
<d>data1</d>
<d>data2</d>
<d>data3</d>
</row>
<row>
<d>data4</d>
<d>data5</d>
<d>data6</d>
</row>
</table>
</root-element>
了解更多信息