将XML文件转换为Java LinkedHashSet
我有一个XML文件,需要将其内容解析为将XML文件转换为Java LinkedHashSet,java,xml,collections,jaxb,Java,Xml,Collections,Jaxb,我有一个XML文件,需要将其内容解析为LinkedHashSet,它存储我自己类的对象。例如,集合类: public class person{ private long id; private String name; private int age; } 所以XML应该是这样的: <root> <person1> <id>1</id> <name>Bo
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>
1.
上下快速移动
25
2.
亚历克斯
15
等等。
我发现了一些关于JAXB的东西,但总是有只针对一个对象的示例,而不是针对整个集合的示例。因此,我的问题是如何将XML转换为
LinkedHashSet
您可以尝试类似的方法(仅供参考,我稍微更改了XML)
雇员阶级
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;
}
}
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;
}
}
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;
}