XML转换成JavaBean
用Dom4j和SAX解析配置文件成java Bean对象
分类: java 2011-08-05 11:13 138人阅读 评论(0) 收藏 举报
[java] view plaincopy
用Dom4j和SAX两种方式将如下配置文件解析成java Bean对象。配置文件(config.xml)如下:pre class=”html” name=”code”?xml version=”1.0″ encoding=”UTF-8″?
Beans
Bean className=”Test” classComment=”测试类”
Field name=”name” type=”String” comment=”名字” /
Field name=”sex” type=”Integer” comment=”性别” /
/Bean
Bean className=”Test1″ classComment=”测试类1″
Field name=”name1″ type=”String” comment=”名字1″ /
Field name=”sex1″ type=”Integer” comment=”性别1″ /
/Bean
/Beans
[java] view plaincopy
首先定义java的三个类Beans、Bean、Field 来承载配置文件的节点,类定义如下:
[java] view plaincopy
/**
* 总对象
* @author
*/
public class Beans {
private ArrayListBean listBean = new ArrayListBean();;
public ArrayListBean getListBean() {
return listBean;
}
public void setListBean(ArrayListBean listBean) {
this.listBean = listBean;
}
}
/**
* 一个Class Bean
* @author
*
*/
public class Bean {
private String className;//类名
private String classComment;//类注释
private ArrayListField listField = new ArrayListField();
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getClassComment() {
return classComment;
}
public void setClassComment(String classComment) {
this.classComment = classComment;
}
public ArrayListField getListField() {
return listField;
}
public void setListField(ArrayListField listField) {
this.listField = listField;
}
}
/**
* Bean 中的属性对象
* @author
*
*/
public class Field {
//类型
private String type;
//字段名字
private String name;
//字段注释
private String comment;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
第一种方式:通过Dom4j的方式解析xml文件:
[java] view plaincopy
[java] view plaincopy
/**
* 将xml格式的字符串转成Beans对象
* @param xml
* @return
*/
public static Beans parseXml(String xml)
{
Beans returnObj = new Beans();
Document doc = null;
try{
// doc = DocumentHelper.parseText(xml); 原版转的是用的这种方式获取document对象,但是测试出错。自己换成了下面方式获取document对象就对了。
SAXReader reader = new SAXReader();
doc = reader.read(new File(xml));
Element root = doc.getRootElement();
//obj list
List list_el = root.elements();
if(list_el !=null list_el.size()0)
{
for(int i =0;ilist_el.size();i++)
{
Element obj_el = (Element) list_el.get(i);
//解析obj 节点
Bean obj = parseObj(obj_el);
returnObj.getListBean().add(obj);
}
}
}catch(Exception e){
e.printStackTrace();
}
return returnObj;
}
/**
* 解析Bean节点
* @param obj_el
* @return
*/
private static Bean parseObj(Element obj_el)
{
Bean obj = new Bean();
obj.setClassName(obj_el.attributeValue(“className”));
obj.setClassComment(obj_el.attributeValue(“classComment”));
//获取field 列表
List list_field = obj_el.elements();
if(list_field != null list_field.size() 0)
{
for(int i = 0;ilist_field.size();i++)
{
Element field_el = (Element)list_field.get(i);
//解析field节点
Field field = parseField(field_el);
obj.getListField().add(field);
}
}
return obj;
}
/**
* 解析Field属性
* @param field_el
* @return
*/
private static Field parseField(Element field_el)
{
Field field = new Field();
List list_attr = field_el.attributes();
if(list_attr != null list_attr.size() 0)
{
for(int i=0;ilist_attr.size();i++)
{
Attribute field_attr = (Attribute)list_attr.get(i);
String key = field_attr.getName();
String value = field_attr.getText();
if(key.equals(“name”))
{
field.setName(value);
}
else if(key.equals(“type”))
{
field.setType(value);
}
else if(key.equals(“comment”))
{
field.setComment(value);
}
}
}
return field;
}
怎么用jaxb技术将xml转成javabean
Java代码
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement(name=”module”)
public class Module extends Metadata{
@XmlAttribute(name=”name”)
public String name;
@XmlAttribute(name=”template”)
public String template;
@XmlElement
public Resources resources;
@XmlElement
public HeaderItems headerItems;
@XmlElement
public Properties properties;
@XmlElement
public BodyItems bodyItems;
@XmlTransient
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlTransient
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
@XmlTransient
public Resources getResources() {
return resources;
}
public void setResources(Resources resources) {
this.resources = resources;
}
@XmlTransient
public HeaderItems getHeaderItems() {
return headerItems;
}
public void setHeaderItems(HeaderItems headerItems) {
this.headerItems = headerItems;
}
@XmlTransient
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@XmlTransient
public BodyItems getBodyItems() {
return bodyItems;
}
public void setBodyItems(BodyItems bodyItems) {
this.bodyItems = bodyItems;
}
}
Moduel对象其中一个对象属性:
Java代码
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class HeaderItems extends Metadata {
@XmlElement(name=”field”)
private ListField fields;
@XmlTransient
public ListField getFields() {
return fields;
}
public void setFields(ListField fields) {
this.fields = fields;
for (int i=0; ifields.size(); i++)
fields.get(i).setHeaderItem(true);
}
public void clear() {
fields.clear();
}
}
Java代码
package com.morningstar.wfe.metadata.node;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
public class Map extends Datasource {
@XmlAttribute(name=”name”)
public String name;
@XmlAttribute(name=”type”)
public String type;
@XmlAttribute(name=”url”)
public String url;
@XmlElement
public Entries entries;
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public void setEntries(Entries entries) {
this.entries = entries;
}
@XmlTransient
public String getName() {
return name;
}
@XmlTransient
public String getType() {
return type;
}
@XmlTransient
public Entries getEntries() {
return this.entries;
}
@XmlTransient
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int size() {
if (entries == null) return 0;
return entries.size();
}
public Entry get(int index) {
if (entries == null) return null;
return entries.get(index);
}
public ListEntry getEntriesList() {
return entries.getEntryList();
}
}
最后XML闪亮登场:
Java代码
?xml version=”1.0″ encoding=”UTF-8″?
module name=’showcase’ template=’showcase.ftl’
resources
map name=’css’ type=’static’
entries
entry label=”text_a1″ value=”text_a1″/entry
entry label=”text_a2″ value=”text_a2″/entry
entry label=”text_a3″ value=”text_a3″/entry
entry label=”text_c1″ value=”text_c1″/entry
entry label=”text_c2″ value=”text_c2″/entry
/entries
/map
map name=’status’ type=’ws’ url=”xxxx”
/map
map name=’author’ type=’file’ url=”xxxx”
/map
/resources
headerItems
field name=’active1′ type=’checkbox’ datasource=’css’
multiple=’false’ /
field name=’title1′ type=’text’ format=”string” required=”true”/
field name=’radio11′ type=’radio’ datasource=’css’/
field name=’url11′ type=’url’ format=”string”/
field name=’dropdownlist111′ type=’select’ datasource=’css’ multiple=”true” height=”80″ width=”100″/
field name=’title22′ type=’textarea’ width=”200″ height=”100″ spellCheck=”true” format=”string” required=”true”/
/headerItems
properties
field name=’active12′ type=’checkbox’ datasource=’status’
multiple=’false’ /
field name=’title12′ type=’date’ format=”int” /
field name=’email11′ type=’email’ visible=”true” /
/properties
bodyItems
field label=”Name” name=”name” type=”text” visible=”false”
editable=”false”/field
field name=”readings_list” type=”datatable” action=”insert,remove”
columns
field label=”Title” name=”rSource” type=”text” visible=”true” width=”30″/
field label=”URL” name=”rURL” type=”text” visible=”true” width=”40″/
field label=”Date” name=”rDate” type=”text” visible=”true” width=”50″/
field label=”Source” name=”rSource” type=”text” visible=”true” width=”60″/
/columns
/field
/bodyItems
/module
Metadata是一个抽象类,描述了些 ID NAME VALUE基本属性 没什么特别的
关于XML转java对象的操作:
Java代码
public static Module parse(String metadata) throws MetadataParserException {
Module module = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Module.class);
Unmarshaller um = jaxbContext.createUnmarshaller();
module = (Module)um.unmarshal(new ByteArrayInputStream(metadata.getBytes()));
} catch (JAXBException e) {
log.warn(“JAXB castor failed to convert the metadata to module instance by {}”,e.getMessage());
throw new MetadataParserException();
}
return module;
}
这样的话传进XML的字符串,就可以解析出这个JAVA对象。完全不用写任何过多的代码。岂不爽哉?!!!!
附一个java bean = xml 的unmi同志原创文档,主要是比较Jaxb和castor。
如何用java读取xml文件
1利用dom对象,直接查找标签
2利用工具类,比如xmlbean,直接将xml映像成javabean