import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
public class XMLUtils {
private XMLUtils() {
// Not supposed to be instantiated.
}
public static Object parseXMLToObject(String filePath, Class<?> objectClass) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(objectClass);
javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller();
File file = new File(filePath);
return unmarshaller.unmarshal(file);
}
}
<?xml version="1.0" encoding="gb2312" standalone="yes"?>
<root>
<person>
<password>123</password>
<username>nihao</username>
</person>
<person>
<password>1233</password>
<username>nihao3</username>
</person>
</root>
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Root {
private List<Person> person;
public List<Person> getPerson() {
return person;
}
public void setPerson(List<Person> person) {
this.person = person;
}
}
class Person{
String password = "password";
String username = "username";
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}