XML与Java之间相互转换(1.Java对象转换成XML(Marshaller) 2.XML转换成java对象(Unmarshaller) )
Posted grain-of-wood
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML与Java之间相互转换(1.Java对象转换成XML(Marshaller) 2.XML转换成java对象(Unmarshaller) )相关的知识,希望对你有一定的参考价值。
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("[email protected]"); //将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) )的主要内容,如果未能解决你的问题,请参考以下文章
Java&Xml教程JAXB实现XML与Java对象转换