使用JAXB編組
例子:如果你想讀一個customer.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>Martin</name>
</customer>
第1步:映射的XML類文件
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
Step 2: Write a reader class
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class ReadXml {
public static void main(String[] args) throws JAXBException {
File file = new File("D:\\customer.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println("Name :" + customer.getName());
System.out.println("Age :" + customer.getAge());
System.out.println("Id :" + customer.getId());
}
}
output:
Name :Martin
Age :29
Id :100
利用圖書館。如果您的家中已經有螺絲刀,您不會用錘子驅動螺絲釘;-) –