利用 JavaBean 读取xml文件 (一)

2014-11-24 10:53:17 · 作者: · 浏览: 0

[html]

package demo20130531; 

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Article {

private String title;

private String author;

private String email;

private String date;

private Authors authors;

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;
}

public Authors getAuthors() {
return authors;
}

public void setAuthors(Authors authors) {
this.authors = authors;
}


}


< xml version="1.0" encoding="UTF-8" >
helloctlctl_cn@163.com1991-06-2922M
河南

 
package demo20130531; 

public class Authors {
private int age;
private String sex;//不可以是char类型
private String address;
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String toString() {
return "age:" + age +
" sex:" + sex +
" address:" + address;
}
}


package demo20130531; 

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

//根元素的标签名为articles
@XmlRootElement(name = "articles")
public class ArticleData {

//articles元素下有多个article元素
List
article = new ArrayList
();

public List
getArticle() {
return article;
}

public void setArticle(List
article) {
this.article = article;
}

public static void main(String[] args) throws IOException {

// 创建xml文档对象,其保存在E盘的根目录下的article.xml文件
File xmlFile = new File("src2/demo20130531/article.xml");
// System.out.println(xmlFile.getAbsolutePath());
// System.out.println(xmlFile.getParent());
if(!xmlFile.exists())
xmlFile.createNewFile();
// 声明JAXBContext上下文对象
JAXBContext context;
try {
// 通过指定映射的类创建上下文
context = JAXBContext.newInstance(ArticleData.class);
// 通过上下文创建xml转化java的对象Unmarshaller
Unmarshaller u = context.createUnmarshaller();
// 将xml数据转换成java对象
ArticleData data = (ArticleData) u.unmarshal(xmlFile);
// 获得所有的article数据
List
articles = data.getArticle();
for (Article a : articles) {
System.out.println("-------------------------");
System.out.println(a.getAuthor