castor对xml、object数据进行换转Demo(二)

xml格式数据数据通过castor转换成javabean对象

CastorXmlToBeanTest.java

package com.wj.castor;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.XMLContext;

/**
 * 
 * 根据xml数据生成bean对象
 * 
 * 测试:
 * (A):不要Mapping.xml
 * (B):加入Mapping.xml进行
 * 
 * @author  wjcom
 * @version  [版本号, 2010-7-28]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class CastorXmlToBeanTest 
{
	
	private static final Log LOGGER = LogFactory
			.getLog(CastorXmlToBeanTest.class);
	
	private static Unmarshaller unmarshaller;
	
	/**
	 * 静态块加载mapping.xml读取解析xml的规则
	 * 创建Unmarshaller对象
	 */
	static 
	{
		try 
		{
			Mapping mapping = new Mapping();

			String url = "D:\\eclipse3.5.1\\workspace\\learning\\src\\com\\wj\\castor\\mapping_xmlTobean.xml";
			mapping.loadMapping(url);
			XMLContext context = new XMLContext();
			context.addMapping(mapping);
			unmarshaller = context.createUnmarshaller();
		} 
		catch (Exception e) 
		{
			LOGGER.info(e.getMessage());
		}
	}

	/**
	 * 运行体
	 */
	public static void main(String[] args) 
	{
		PersonCommonDataContext p = findPersonCommonData();
		LOGGER.info(p);
	}
	
	/**
	 * 读取xml数据
	 * @return
	 */
	public static PersonCommonDataContext findPersonCommonData() 
	{
		File configFile = new File(
				"D:\\eclipse3.5.1\\workspace\\learning\\src\\com\\wj\\castor\\person2.xml");

		if (!configFile.exists() || !configFile.canRead()) 
		{
			return null;
		}

		InputStream inputStream = null;

		PersonCommonDataContext data = null;

		try 
		{
			inputStream = new FileInputStream(configFile);

			if (null != unmarshaller) 
			{
				data = read(inputStream);
			}
		}
		catch (Exception e) 
		{
			LOGGER.info(e.getMessage());
		}
		return data;

	}

	/**
	 * 从流中读取数据
	 * @param input
	 * @return
	 */
	public static PersonCommonDataContext read(InputStream input) 
	{
		PersonCommonDataContext context = null;
		try 
		{
			if (null != unmarshaller) 
			{
				context = (PersonCommonDataContext) unmarshaller
						.unmarshal(new InputStreamReader(input));

			}
		} 
		catch (Exception e) 
		{
			LOGGER.info(e.getMessage());
		}
		return context;
	}

	

}



PersonCommonDataContext.java

package com.wj.castor;

import java.util.ArrayList;
import java.util.List;

public class PersonCommonDataContext
{
	private List<Person> simpleProperties  = new ArrayList<Person>(5);

	public List<Person> getSimpleProperties() {
		return simpleProperties;
	}

	public void setSimpleProperties(List<Person> simpleProperties) {
		this.simpleProperties = simpleProperties;
	}

	@Override
	public String toString() {
		return "PersonCommonDataContext [simpleProperties=" + simpleProperties
				+ "]";
	}

	
}

你可能感兴趣的:(java,apache,bean,xml)