您可以执行以下操作:
根
如果该字段更改为List<Animal>
或,则此示例的工作方式相同ArrayList<Animal>
。
package forum13178824;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="animal")
private Animal[] animals;
}
动物
package forum13178824;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Animal {
private String name;
}
演示
package forum13178824;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum13178824/input.xml");
Root root = (Root) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
输入.xml/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<animal>
<name>barack</name>
</animal>
<animal>
<name>mitt</name>
</animal>
</root>
了解更多信息