将XML解组为数组

Oli*_* J. 9 xml jaxb unmarshalling

我想将XML文件解组成元素数组.

示例:

<root>
   <animal>
      <name>barack</name>
   </animal>
   <animal>
      <name>mitt</name>
   </animal>
</root>
Run Code Online (Sandbox Code Playgroud)

我想要一组动物元素.

当我尝试

JAXBContext jaxb = JAXBContext.newInstance(Root.class);
Unmarshaller jaxbUnmarshaller = jaxb.createUnmarshaller();
Root r = (Root)jaxbUnmarshaller.unmarshal(is);
system.out.println(r.getAnimal.getName());
Run Code Online (Sandbox Code Playgroud)

这个显示mitt,最后一个动物.

我想这样做:

Animal[] a = ....
// OR
ArrayList<Animal> = ...;
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

bdo*_*han 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;

}
Run Code Online (Sandbox Code Playgroud)

动物

package forum13178824;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Animal {

    private String name;

}
Run Code Online (Sandbox Code Playgroud)

演示

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

input.xml中/输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <animal>
        <name>barack</name>
    </animal>
    <animal>
        <name>mitt</name>
    </animal>
</root>
Run Code Online (Sandbox Code Playgroud)

欲获得更多信息