Recently used to record a self-written demo
Using the @xmlrootelement annotation on the root element, name is the element name
child element attributes use @xmlelement,name as the element name
If there are attributes, such as <emplyee hobby= "Swim", then use @xmlattribute,name as the property 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 classes
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); } }