使用jaxb操作Java与xml之间的转换非常简单,看个例子就明白了。
//javaBean-->xml
@Test
public void test1() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Marshaller marshaller = jaxbContext.createMarshaller();
User user1 = new User("张三", "zhangsan", 123);
marshaller.marshal(user1, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
//xml-->javaBean
@Test
public void test2() {
try {
String xml = "<user><money>123</money>"
+ "<password>zhangsan</password><username>张三</username>"
+ "</user>";
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
User user = (User) um.unmarshal(new StringReader(xml));
System.out.println(user.getUsername() + "," + user.getMoney());
} catch (JAXBException e) {
e.printStackTrace();
}
}
时间: 2024-12-20 05:31:09