我想将XML文件解组成元素数组。
示例:
<root>
<animal>
<name>barack</name>
</animal>
<animal>
<name>mitt</name>
</animal>
</root>
我想要一组动物元素。
当我尝试
时JAXBContext jaxb = JAXBContext.newInstance(Root.class);
Unmarshaller jaxbUnmarshaller = jaxb.createUnmarshaller();
Root r = (Root)jaxbUnmarshaller.unmarshal(is);
system.out.println(r.getAnimal.getName());
这个显示mitt
,最后一个动物。
我想这样做:
Animal[] a = ....
// OR
ArrayList<Animal> = ...;
我该怎么办?
答案 0 :(得分:11)
您可以执行以下操作:
<强>根强>
如果字段已更改为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);
}
}
<强> input.xml中/输出强>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<animal>
<name>barack</name>
</animal>
<animal>
<name>mitt</name>
</animal>
</root>
了解更多信息