您好,登錄后才能下訂單哦!
xml和bean之間轉化
//bean
@XmlRootElement(name = "register")@XmlAccessorType(XmlAccessType.PROPERTY)
br/>@XmlAccessorType(XmlAccessType.PROPERTY)
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}bean反序列化xml:
@Test
br/>bean反序列化xml:
@Test
try {
User user=new User();
user.setName("zhan");
user.setAge("23");
JAXBContext context = JAXBContext.newInstance(User.class);
Marshaller marshaller = context.createMarshaller();
// 是否格式化
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 是否省略頭文件
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
StringWriter swriter = new StringWriter();
// 將XML內容打印為字符串
marshaller.marshal(user, swriter);
String xmlString = swriter.getBuffer().toString();
System.out.println(xmlString);
}catch (Exception e){
e.printStackTrace();
}
}
xml序列化成bean:@Test
br/>@Test
try {
String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<register>\n" +
" <name>zhan</name>\n" +
" <age>23</age>\n" +
"</register>";
JAXBContext context = JAXBContext.newInstance(User.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Object unmarshal = unmarshaller.unmarshal(new StringReader(xml));
System.out.println(unmarshal.toString());
} catch (JAXBException e) {
e.printStackTrace();
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。