我想将 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> = ...;
请问我该怎么办?
您可以执行以下操作:
Root
如果该字段更改为,此示例将同样工作List<Animal>
or ArrayList<Animal>
.
package forum13178824;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlElement(name="animal")
private Animal[] animals;
}
Animal
package forum13178824;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Animal {
private String name;
}
Demo
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>
了解更多信息
- http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
- http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)