, use @XmlAttribute, name is the attribute name"/> , use @XmlAttribute, name is the attribute name">
Recently used, record a demo written by yourself
Use @XmlRootElement annotation on the root element, name is the element name
Use @XmlElement for child element attributes, and name is the element name
If there is an attribute, such as af8eeb6dad41dcead93f4e104da1ea26, use @XmlAttribute, and name is the attribute name
xml:
<?xml version="1.0" encoding="UTF-8"?> <employees> <employee> <userId>johnsmith@company.com</userId> <password>abc123_</password> <name>John Smith</name> <age>24</age> <gender>Male</gender> </employee> <employee> <userId>christinechen@company.com</userId> <password>123456</password> <name>Christine Chen</name> <age>27</age> <gender>Female</gender> </employee> </employees>
Employees:
import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "employees") public class Employees { private List<Employee> eList; @XmlElement(name = "employee") public List<Employee> geteList() { return eList; } public void seteList(List<Employee> eList) { this.eList = eList; } }
Employee:
import javax.xml.bind.annotation.XmlElement; public class Employee { private String userId; private String password; private String name; private String age; private String gender; @Override public String toString() { return "Employee [userId=" + userId + ", password=" + password + ", name=" + name + ", age=" + age + ", gender=" + gender + "]"; } @XmlElement(name="userId") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @XmlElement(name="password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @XmlElement(name="name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name="age") public String getAge() { return age; } public void setAge(String age) { this.age = age; } @XmlElement(name="gender") public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
Parsing class
public static void main(String[] args) throws JAXBException { JAXBContext context = JAXBContext.newInstance(Employees.class); Unmarshaller createUnmarshaller = context.createUnmarshaller(); Object unmarshal = createUnmarshaller.unmarshal( new File("D:/java/workspacedev/JavaTest/xml/employees.xml")); Employees em = (Employees) unmarshal; List<Employee> list = em.geteList(); for (Employee employee : list) { System.out.println(employee); } }
Related recommendations:
The above is the detailed content of Convert xml to Bean instance parsing in java (pure code). For more information, please follow other related articles on the PHP Chinese website!