分享一个解析xml的小工具

因为项目的需求,自己写了一个解析xml的工具:如下, if  you want to it,please read the class of  readXML;action :the model must be impl the interface of IModel,自定义的model,

譬如我们有个xml,这里是自定义的

<?xml version="1.0" encoding="UTF-8"?>
<root>

    <Scenes>
        <base>
            <id>1</id>
            <name> 亚特兰蒂斯</name>
        </base>
    </Scenes>

    <!--任务模块-->
    <Tasks>
        <base>
            <id>任务ID</id>
            <name>kill monster</name>
            <preID>123</preID>
            <minLevel>23</minLevel>
            <details>详细说明</details>
            <description> 任务描述</description>
        </base>
    </Tasks>




</root>

接口model

package game.model.gameData;

import java.io.Serializable;

/**
 * @auther:陈磊 <br/>
 * Date: 12-12-10<br/>
 * Time: 下午1:09<br/>
 * connectMethod:[email protected]<br/>
 */
public interface IModel extends Serializable {
    /**
     * @return
     */
    public Serializable getId();
}
package game.model.gameData;


/**
 * @auther:陈磊 <br/>
 * Date: 12-12-14<br/>
 * Time: 下午6:41<br/>
 * connectMethod:[email protected]<br/>
 * 场景
 * 信息存放在配置文件
 */
public class SceneModel implements IModel{
    /**
     * 场景类型
     */
    public enum SceneType{
        //征战场景:1	地区场景:2	农田场景:3	世界场景:4	银矿场景:5
        Home(0,"主城"),
        Battle(1,"征战"),
        Area(2,"地区"),
        Farm(3,"农田"),
        Wolrd(4,"世界"),
        Mine(5,"银矿"),
        ;
        private final int id;
        private final String name;

        private SceneType(final int id,final String name){
            this.id = id;
            this.name = name;
        }

        public int getId(){
            return id;
        }

        public String getName(){
            return name;
        }
    }

    private Integer id;//地图编号
    private String name; //地图名

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    /**
     * @return
     */
    @Override
    public Integer getId() {
        return id;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
package game.model.gameData;


import com.commons.BaseConfig.config;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * @auther:陈磊 <br/>
 * Date: 12-12-13<br/>
 * Time: 下午5:12<br/>
 * connectMethod:[email protected]<br/>
 *  游戏服务器基础model配置加载
 */
@SuppressWarnings("unchecked")
public class GameDataCenter {
    private static final Logger LOG = LoggerFactory.getLogger(GameDataCenter.class);
    public final static SimpleDateFormat DATEFORMAT_SEC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static Map<Integer, SceneModel> SceneModelMap = new HashMap<Integer, SceneModel>();

    public static Map<Integer, TaskModel> TaskModelMap = new HashMap<Integer, TaskModel>();
    /**
     * 加载物品配置文件
     */
    public void loads(){
        try {
            this.parseGoodsXML(config.Model_CONFIG);
        } catch (FileNotFoundException e) {
            LOG.warn("FileNotFoundException",e);//To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
      枚举系统基础配置信息
                <Scenes>
                     <base>
                         <id>1</id>
                         <name> 亚特兰蒂斯</name>
                     </base>
                 </Scenes>

     Scenes:modelType
     base:game of  node
     */
    private enum readXML{
        SceneModel("Scenes", SceneModel.class,SceneModelMap),
        TaskModel("Tasks",TaskModel.class,TaskModelMap);

        private final String id;
        private final Class<?> cls;
        private  Map map;

        private readXML(final String id,final Class<?> cls,Map map){
            this.id = id;
            this.cls= cls;
            this.map = map;
        }

        public String getId() {
            return id;
        }

        public Class<?> getCls() {
            return cls;
        }


        public Map getMap() {
            return map;
        }
    }


    /**
     * 读取配置文件
     */
    private void parseGoodsXML(String dataxml) throws FileNotFoundException{
        InputStream inputStream = new FileInputStream(dataxml);
        Document doc = null;
        try {
            SAXReader saxReader = new SAXReader();
            doc = saxReader.read(inputStream);
        } catch (DocumentException e) {
            LOG.error("DocumentException", e);
        }
        if (doc != null) {
            Element root = doc.getRootElement();
            for(readXML xmlRoot: readXML.values()){
                String flag=xmlRoot.getId();
                Element element = root.element(flag);
                Map<String,String> map = new HashMap<String,String>();
                if (element != null) {
                    for(Iterator vos = element.elementIterator(config.GAME_Goods_NODE); vos.hasNext(); ) {
                        Element vo = (Element) vos.next();
                        for(Iterator values = vo.elementIterator(); values.hasNext(); ) {
                            Element value = (Element) values.next();
                            map.put(value.getName(), (String)value.getData());
                        }
                        Object obj =run2Object(map, xmlRoot.getCls());
                        IModel model = (IModel)obj;
                        LOG.info("编号:---》"+model.getId());
                        xmlRoot.getMap().put(model.getId(), model);
                    }

                }
            }
        }

    }

    /**
     * 通过反射,注入model属性
     * @param map
     * @param classType
     * @return  Object
     */
    public  Object run2Object(Map<String, String> map,Class classType){
        Object objectCopy = null;
        try {
            objectCopy = classType.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获得对象的所有属性
        Field[] fields = classType.getDeclaredFields();

        for (Field field : fields) {
            // 获取数组中对应的属性
            String fieldName = field.getName();
            String stringLetter = fieldName.substring(0, 1).toUpperCase();

            // 获得相应属性的setXXX方法名称
            String setName = "set" + stringLetter + fieldName.substring(1);
            // 获取相应的setXXX方法
            Method setMethod = null;
            try {
                setMethod = classType.getMethod(setName, new Class[] {field
                        .getType()});
            } catch (Exception e) {
                continue;
            }

            // 调用拷贝对象的setXXX方法
            try {
                Class classes[]  = setMethod.getParameterTypes();
                Object value = null;
                String fieldValue = map.get(fieldName);
                if(fieldValue == null || "".equals(fieldValue)){

                }else if(classes[0].equals(Date.class)){
                    value = DATEFORMAT_SEC.parse(fieldValue);
                }else if(classes[0].equals(Integer.class)){
                    value = Integer.valueOf(fieldValue);
                }else if(classes[0].equals(Long.class)){
                    value = Long.valueOf(fieldValue);
                }else if(classes[0].equals(Float.class)){
                    value = Float.valueOf(fieldValue);
                }else if(classes[0].equals(Double.class)){
                    value = Double.valueOf(fieldValue);
                }else
                    value = fieldValue;
                setMethod.invoke(objectCopy, new Object[] {value});
            } catch (Exception e) {
                continue;
            }

        }
        return objectCopy;
    }
}
ok,如果你有心,并且代码拷贝下了,应该是可以run的,你会觉得这个不错哦, 有问题的 留言

你可能感兴趣的:(分享一个解析xml的小工具)