gpt4 book ai didi

java - 将日期存储在 XML 标签中

转载 作者:行者123 更新时间:2023-11-30 02:01:45 32 4
gpt4 key购买 nike

我有一个关于将日期时间存储到 Jaxb 中的问题。目前我有这个:

XML:

<reconcile>
<start_date>2018-04-08T11:02:44</start_date>
<end_date>2018-04-08T11:02:44</end_date>
<page>1</page>
</reconcile>

JaxB 对象:

    @XmlElement(name = "start_date")
public Date start_date;
@XmlElement(name = "end_date")
public Date end_date;
@XmlElement(name = "page")

我应该使用字符串作为 start_date 和 end_date 还是需要在使用 JAXB 之前转换字符串 2018-04-08 11:02:44 ?您能分享一下最佳实践吗?

最佳答案

https://github.com/jaxb-java-time-adapters/jaxb-java-time-adapters#releases 添加了用于 java.time 的 JAXB

然后像这样注释:

@XmlRootElement
public class Reconcile {
@XmlElement(name = "start_date")
@XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
public LocalDateTime start_date;

@XmlElement(name = "end_date")
@XmlJavaTypeAdapter(LocalDateTimeXmlAdapter.class)
public LocalDateTime end_date;

@XmlElement(name = "page")
public int page;
}

测试

Reconcile reconcile = new Reconcile();
reconcile.start_date = LocalDateTime.of(2018, 4, 8, 11, 2, 44);
reconcile.end_date = LocalDateTime.of(2018, 11, 8, 11, 2, 44);
reconcile.page = 1;

JAXBContext jaxbContext = JAXBContext.newInstance(Reconcile.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(reconcile, System.out);

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<reconcile>
<start_date>2018-04-08T11:02:44</start_date>
<end_date>2018-11-08T11:02:44</end_date>
<page>1</page>
</reconcile>

关于java - 将日期存储在 XML 标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635760/

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