gpt4 book ai didi

使用 JAXB 将 Java 列表转换为 XML 编码不起作用?

转载 作者:行者123 更新时间:2023-11-30 07:35:17 26 4
gpt4 key购买 nike

在发布此问题之前,我对类似类型问题的堆栈交换答案进行了大量研究。我也尝试了很多解决方案来解决谷歌的问题。最后我想我可以在这里问问题:

  1. 我正在尝试使用 JAXB 编码过程将 Java 帐户对象列表转换为 XML。但预期的是下面的前 15 行正确的 xml,当前生成的是最后 2 行代码:

这里是:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<accounts>
<account>
<accountName>Media Team </accountName>
<ownerName>Support Team</ownerName>
<ownerEmail>sbjba@gmail.com</ownerEmail>
<ownerId>1221323</ownerId>
<account>
<account>
<accountName>Delivery</accountName>
<ownerName>jadajsnfd</ownerName>
<ownerEmail>bfjaja@gmail.com</ownerEmail>
<ownerId>82487282</ownerId>
</account>
</accounts>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
</accounts>

这是 Accounts 类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "accounts")
public class Accounts {
@XmlElement(name = "account", type = Account.class)
private List<Account> accounts = new ArrayList<Account>();
public Accounts(){
}
public Accounts(List<Account> accounts) {
}
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}

这是帐户类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "account")
public class Account {
String accountName;
String ownerName;
String ownerEmail;
String ownerId;
//All setters and getters are here public
}

最后这是我的代码:

File videosFile = new File("C:/AccountInfo.xml");
List<Account> accounts = null;
List<KalturaMediaEntry> mediaList = null;
mediaList = getAllLatestMedia();
if (mediaList.size() >= 1) {
System.out.println("mediaList.size() ---------->"
+ mediaList.size());
accounts = setMediaDataByAccount(mediaList);
if (accounts.size() >= 1) {
System.out.println("videos.size() --------->"
+ accounts.size());
marshalVideos(accounts, videosFile);
}
}

public static void marshalVideos(List<Account> accounts,
File videosFile) throws JAXBException, IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(videosFile, true), "UTF-8"));
final Marshaller m = JAXBContext.newInstance(Accounts.class)
.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(new Accounts(accounts), writer);
writer.close();
}

我也尝试过添加 @XMLSeeAlso 注释等解决方案。但不工作。请帮我解决这个问题。

提前致谢,拉吉

最佳答案

Accounts 的构造函数中,您不使用 Account 列表:

public Accounts(List<Account> accounts) {
}

所以,将其更改为

public Accounts(List<Account> accounts) {
this.accounts = accounts;
}

关于使用 JAXB 将 Java 列表转换为 XML 编码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35482449/

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