将 XML 文件转换为 Java LinkedHashSet



我有一个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;
}

最新更新