gpt4 book ai didi

xml - 将 XML 解码为数组

转载 作者:数据小太阳 更新时间:2023-10-29 01:44:52 26 4
gpt4 key购买 nike

我想将 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[] a = ....
// OR
ArrayList<Animal> = ...;

请问我该怎么做?

最佳答案

您可以执行以下操作:

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

了解更多信息

关于xml - 将 XML 解码为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13178824/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com