gpt4 book ai didi

java - 将 XML 文件转换为 Java LinkedHashSet

转载 作者:行者123 更新时间:2023-12-01 18:32:18 24 4
gpt4 key购买 nike

我有一个 XML 文件,我需要将其内容解析为 LinkedHashSet,它存储我自己的类的对象。例如集合类:

public class person{ 
private long id;
private String name;
private int age;
}

所以 XML 应该是这样的:

<root> 
<person1>
<id>1</id>
<name>Bob</name>
<age>25</age>
</person1>
<person2>
<id>2</id>
<name>Alex</name>
<age>15</age>
</person2>
</root>

等等。我用 JAXB 找到了一些东西,但总是只有一个对象的示例,而不是整个集合的示例。所以我的问题是如何将 XML 转换为 LinkedHashSet

最佳答案

你可以尝试这样的事情(仅供引用,我稍微改变了xml)

<employee>
<person>
<id>1</id>
<name>Bob</name>
<age>25</age>
</person>
<person>
<id>2</id>
<name>Alex</name>
<age>15</age>
</person>
</employee>

人的类别

public class Person {

private long id;
private String name;
private int age;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

员工类别

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.LinkedHashSet;

@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {

@XmlElement(name = "person")
private LinkedHashSet<Person> listOfPerson;

public LinkedHashSet<Person> getListOfPerson() {
return listOfPerson;
}
}

最后我们可以获得这些数据(getEmployee().getListOfPerson() 做你想做的事)) )

public Employee getEmployee() throws JAXBException {
File file = new File("data.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employee employee = (Employee) jaxbUnmarshaller.unmarshal(file);

return employee;
}

关于java - 将 XML 文件转换为 Java LinkedHashSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60139479/

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