将XML解组为数组 [英] Unmarshal XML into arrays

查看:108
本文介绍了将XML解组为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to unmarhal XML file into array of elements.

示例:

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

我想要一个Animal元素数组。

I would like an array of Animal elements.

当我尝试

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

此显示 mitt ,最后一只动物。

this display mitt, the last Animal.

我想这样做:

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

我该怎么办?

推荐答案

您可以执行以下操作:

Root

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

更多信息

  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
  • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html

这篇关于将XML解组为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆