当前位置:编程学习 > XML/UML >>

XML解析工具类

        由于以前在解析XML的时候,每次都要采用获取XML中的属性名来获取对应的值,每一个bean类都要写一个XML解析器。这将会使代码变得更加冗余,而没办法做到高度抽象。幸亏Java有自身的内省机制,Introspector与反射类似,主要是对Java Bean属性、方法等的一种处理方法。
 
package com.ibm.cn.xml;
 
import java.beans.BeanInfo;
importjava.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
importjava.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import org.dom4j.Document;
import org.dom4j.Element;
importorg.dom4j.io.SAXReader;
 
 
/**
 * XML解析工具类
 * @author javamickey
 * @date 2012-11-01
 * @version 2.0
 */
public class ParsersUtil {
 
 
                /**
                 * 通过XML文件名,来解析XML对象,此函数只针对XML中存在一个bean值的情况
                 * @paramfileName XML文件名
                 * @param typebean类名
                 * @return 单个bean对象
                 * @throwsException
                 */
                public static Object parserXMLByFileName(StringfileName, Class<?> type)
                                                throws Exception {
                                Class<? extends Object>beanClass = Class.forName(type.getName());
                                Object bean =beanClass.newInstance();
                                File inputXml = new File(fileName);
                                SAXReader saxReader = new SAXReader();
                                try {
                                                Document document =saxReader.read(inputXml);
                                                Element element =document.getRootElement();
                                                BeanInfo beanInfo =Introspector.getBeanInfo(type);
                                                PropertyDescriptor[]propertyDescriptors = beanInfo.getPropertyDescriptors();
                                                for(PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                                                                StringpropertyName = propertyDescriptor.getName();
                                                                for(Iterator<?> iterator = element.elementIterator(); iterator.hasNext();) {
                                                                                ElementemployeeElement = (Element) iterator.next();
                                                                                if(!propertyName.equals("class")) {
                                                                                                MethodreadMethod = propertyDescriptor.getWriteMethod();
                             &nbs
补充:Web开发 , 其他 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,