将XML反序列化为数组

10
我想将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> = ...;

请问我该怎么做?

1个回答

12

你可以按照以下方式进行操作:

如果将该字段更改为 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>

了解更多信息


1
谢谢!很好的例子和非常棒的博客 ;) - Olivier J.
1
我不得不在Root上加上@XmlAccessorType(XmlAccessType.FIELD)的注释。 - Jaanus
我认为你不能同时使用@XmlAccessorType(XmlAccessType.FIELD)和@XmlElement(name="animal")。你重复映射了相同的元素... - pmartin8
@pmartin8 - 你不能在使用@XmlAccessorType(XmlAccessType.FIELD)的同时在访问器方法(get/set)上放置@XmlElement,但只要你将其放置在字段(实例变量)上,就没问题。 - bdoughan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接