gpt4 book ai didi

java - 使用 POJO 和 JAXB 注释绑定(bind) XML

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:17 24 4
gpt4 key购买 nike

我有以下 xml 格式,我想通过 POJO 和使用 JAXB 注释来绑定(bind)它。 XML 格式如下:

 <datas>
<data>apple<data>
<data>banana<data>
<data>orange<data>
<datas>

我正在尝试通过以下 POJO 绑定(bind)数据:

@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class Datas {

@XmlElement
private List<String> data;

//get/set methods

}

我也试试这个 POJO:

@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class Datas {

@XmlElement
private List<Data> datas;

//get/set methods

}

//

@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class Data{

@XmlElement
private String data;

//get/set methods

}

在第一种情况下,它只检索第一个数据:apple。在第二种情况下不检索任何东西。有人可以帮我提供适当的 POJO 和注释以绑定(bind)所有数据吗?

最佳答案

您可以执行以下选项之一:

选项 #1

数据

package forum11311374;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Datas {

private List<String> data;

//get/set methods

}

了解更多信息


选项#2

数据

package forum11311374;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Datas {

@XmlElement(name="data")
private List<Data> datas;

//get/set methods

}

数据

package forum11311374;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Data{

@XmlValue
private String data;

//get/set methods

}

了解更多信息


以下选项可以与这两个选项一起使用:

input.xml/输出

我已经更新了 XML 文档以包含必要的结束标记。 <data>apple</data>而不是 <data>apple<data> .

<datas>
<data>apple</data>
<data>banana</data>
<data>orange</data>
</datas>

演示

package forum11311374;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Datas.class);

Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11311374/input.xml");
Datas datas = (Datas) unmarshaller.unmarshal(xml);

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(datas, System.out);
}

}

关于java - 使用 POJO 和 JAXB 注释绑定(bind) XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11311374/

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