10

我想将 XML 文件解组为元素数组。

例子 :

<root>
   <animal>
      <name>barack</name>
   </animal>
   <animal>
      <name>mitt</name>
   </animal>
</root>

我想要一组 Animal 元素。

当我尝试

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

本次展示mitt,最后一个Animal。

我想这样做:

Animal[] a = ....
// OR
ArrayList<Animal> = ...;

请问我该怎么办?

4

1 回答 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>

了解更多信息

于 2012-11-01T15:01:19.177 回答