标签:xml文件 bsp err 保存 需要 override tostring create 通过
import javax.xml.bind.annotation.XmlRootElement;
//根元素
@XmlRootElement
public class Article { private String title; private String author; private String email; private String date;
//toString 方法用于将对象里面的内容一一列出
@Override
public String toString() {
return "Article [title=" + title + ", author=" + author + ", email=" + email + ", date=" + date + "]";
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
//将java对象转换成XML
public class JAXBArticle {
public static void main(String[] args) throws JAXBException {
//创建xml文档对象,保存路径为E:\\test.xml
File file=new File("D:\\test.xml");
//声明JAXBContext上下文对象
JAXBContext context=JAXBContext.newInstance(Article.class); //通过上下文对象创建java转换成xml的对象Marshaller; Marshaller m=context.createMarshaller(); //创建xml中需要的数据 Article article=new Article(); article.setTitle("小王子"); article.setAuthor("安托万·德·圣·埃克苏佩"); article.setDate("20180901"); article.setEmail("xiaowangzi@qq.com"); //将java对象转换成XML m.marshal(article,file); System.out.println(article); } }
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
//将XML转换成 java
public class JAXBAticleXML {
public static void main(String[] args) throws JAXBException {
//创建文档对象在D盘中找到test.xml文件
File file=new File("D:\\test.xml");
//声明JAXBContext上下文对象
JAXBContext context=JAXBContext.newInstance(Article.class);
//通过上下文对象创建能将xml文件转换成java的Unmarshaller()对象
Unmarshaller u=context.createUnmarshaller();
//将xml文件转换成java
Article article=(Article) u.unmarshal(file);
//toString方法使用前后article的区别
System.out.println(article);
}
}
XML与Java之间相互转换(1.Java对象转换成XML(Marshaller) 2.XML转换成java对象(Unmarshaller) )
标签:xml文件 bsp err 保存 需要 override tostring create 通过
原文地址:https://www.cnblogs.com/grain-of-wood/p/9586091.html