java框架加载并解析SAX

一、加载配置文件

public class AppMgr {
    private static final String module = AppMgr.class.getName();

    /**
     * 构造器
     */
    private AppMgr() {
        innerStartItems = new ArrayList<StartItem>();
        innerStartItems.add(new Log4j());
        innerStartItems.add(new PlatformConfig());
    }
    /**
     * 实例
     */
    private static AppMgr appMgr = new AppMgr();

    /**
     * 获取实例
     * @return 实例
     */
    public static AppMgr getInstance() {
        return appMgr;
    }
   /**
     * WEB应用主目录应用地址
     */
    private String home = "";

    /**
     * 设置WEB应用主目录地址
     * @param path path
     */
    public void setHome(String path) {
        home = path;
    }

    /**
     * 获取WEB应用主目录地址
     * @return rtnHomeStr rtnHomeStr
     */
    public String getHome() {
        return home;
    }

}

接口

import oracle.core.lmx.CoreException;

/**
 * 启动项
 */
public interface StartItem {
    /**
     * 获取启动项名称

     * @return 启动项名称 */
    public String getName();

    /**
     * 加载启动配置信息
     * @throws CoreException
     */
    public void start() throws CoreException;

    /**
     * 销毁启动资源
     */
    public void stop();
}

二、读取配置文件

import java.io.File;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.platform.core.AppMgr;
import com.platform.core.exception.CoreException;
import com.platform.util.XMLUtils;

/**
 * 系统参数配置
 */
public class PlatformConfig implements StartItem {
    public final static String MODULE = PlatformConfig.class.getName();
    /*
     * (non-Javadoc)
     * @see com.platform.core.start.StartItem#getName()
     */
    public String getName() {
        return "系统参数配置";
    }

    /*
     * (non-Javadoc)
     * @see com.platform.core.start.StartItem#start()
     */
    public void start() throws CoreException {
        // 加载leopard.xml
        String filePath = AppMgr.getInstance().getHome().concat("WEB-INF/leopard.xml");
        Document docInst = doLoadConfFile(filePath);
        AppMgr.getInstance().setVar(MODULE+"$PLATFORM_CONFIG$", XMLUtils.toBean4Xml(docInst.getRootElement()));
    }

    /*
     * (non-Javadoc)
     * @see com.platform.core.start.StartItem#stop()
     */
    public void stop() {

    }

    /**
     * 加载配置文件
     * @param filePath filePath
     * @return docInst docInst
     */
    private Document doLoadConfFile(String filePath) {
        File fileInst = new File(filePath);
        SAXReader saxRInst = new SAXReader();
        Document docInst = null;
        try {
            docInst = saxRInst.read(fileInst);
        } catch (DocumentException e) {
            throw new CoreException(e);
        }
        return docInst;
    }
}

三、XMLUtils

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

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.platform.core.base.Bean;
import com.platform.core.base.IBean;
import com.platform.core.exception.CoreException;

/**
 * 负责xml技术的应用,xml格式转换\xml内容生成、解析
 */
public class XMLUtils {
    /**
     * 将xml文档存储到指定文件路径
     * @param filePath 设定文件路径
     * @param docInst 文档结构实例
     * @return true/false
     */
    public static boolean writeXML2File(String filePath, Document docInst) {
        boolean rtnFlag = true;
        File outFile = new File(filePath);
        boolean canWr = true;
        try {
            if (!outFile.exists()) {
                canWr = outFile.createNewFile();
            }
            if (canWr) {
                XMLWriter xwr = new XMLWriter(new FileOutputStream(outFile), OutputFormat
                    .createPrettyPrint());
                xwr.write(docInst);
                xwr.close();
            }
        } catch (IOException ioe) {
            throw new CoreException(ioe);
        }
        return rtnFlag;
    }

    /**
     * 将xml文档存储到指定文件路径
     * @param filePath 设定文件路径
     * @param elemInst elemInst
     * @return true/false
     */
    public static boolean writeXML2File(String filePath, Element elemInst) {
        Document docInst = DocumentHelper.createDocument(elemInst);
        return writeXML2File(filePath, docInst);
    }

    /**
     * 将xml数据构造成Bean
     * @param elemInst elemInst
     * @return rtnBean 构造完成的Bean/null
     */
    public static IBean toBean4Xml(Element elemInst) {
        IBean rtnBean = new Bean();
        toBean4XML(elemInst, rtnBean);
        return rtnBean;
    }

    /**
     * 解析xml内容转换成IBean数据
     * @param elemInst elemInst
     * @param rtnBean rtnBean
     */
    private static void toBean4XML(Element elemInst, IBean rtnBean) {
        Attribute attr = null;
        int elemCount = elemInst.elements().size(), attrCount = elemInst.attributeCount();
        if (elemCount == 0 && attrCount == 0) {
            return;
        }
        String tmpText = elemInst.getTextTrim();
        if (!"".equals(tmpText)) {
            rtnBean.set(elemInst.getName(), tmpText);
        }
        for (Iterator iterator = elemInst.attributeIterator(); iterator.hasNext();) {
            attr = (Attribute) iterator.next();
            rtnBean.set(attr.getName(), attr.getValue());
        }
        Element tmpElem = null;
        String tmpElemName = null;
        for (Iterator iterator = elemInst.elementIterator(); iterator.hasNext();) {
            tmpElem = (Element) iterator.next();
            tmpElemName = tmpElem.getName();
            Object tmpObj = rtnBean.get(tmpElemName);
            Object resultObj = fromElem(tmpElem);
            if (null == tmpObj) {
                rtnBean.set(tmpElemName, resultObj);
            } else {
                if (tmpObj instanceof List) {
                    ((List) tmpObj).add(resultObj);
                } else {
                    List tmpList = new ArrayList();
                    tmpList.add(tmpObj);
                    tmpList.add(resultObj);
                    rtnBean.set(tmpElemName, tmpList);
                }
            }
        }
    }

    /**
     * innerFromElem
     * @param elemInst elemInst
     * @return rtnObj rtnObj
     */
    private static Object fromElem(Element elemInst) {
        if (elemInst.attributeCount() == 0 && elemInst.elements().size() == 0) {
            return elemInst.getText();
        } else {
            return toBean4Xml(elemInst);
        }
    }

    /**
     * 将Bean数据结构转换成xml结构
     * @param beanInst bean实例
     * @param rootElemName 根节点名称
     * @return rtnElem/null
     */
    public static Element toXML4Bean(IBean beanInst, String rootElemName) {
        return toElem(null == rootElemName ? "Beans" : rootElemName, beanInst);
    }

    /**
     * 将Bean数据结构转换成xml结构
     * @param beanInst bean实例
     * @return rtnElem/null
     */
    public static Element toXML4Bean(IBean beanInst) {
        return toXML4Bean(beanInst, null);
    }

    /**
     * InnerToElement
     * @param name parent ElemName
     * @param beanInst {@link IBean}
     * @return rtnElem {@link Element}
     */
    private static Element toElem(String name, IBean beanInst) {
        Element rtnElem = DocumentHelper.createElement(name);
        Object key, obj;
        for (Iterator iterator = beanInst.getKeys().iterator(); iterator.hasNext();) {
            key = iterator.next();
            obj = beanInst.get(key.toString());
            toElem(rtnElem, key.toString(), obj);
        }
        return rtnElem;
    }

    /**
     * CoreToElement
     * @param elemInst elemInst
     * @param key key
     * @param obj object
     */
    private static void toElem(Element elemInst, String key, Object obj) {
        if (obj instanceof IBean) {
            elemInst.add(toXML4Bean((IBean) obj));
        } else if (obj instanceof List) {
            List tmpList = (List) obj;
            Element tmpElem;
            Object tmpObj;
            for (Iterator iterator = tmpList.iterator(); iterator.hasNext();) {
                tmpElem = DocumentHelper.createElement(key);
                elemInst.add(tmpElem);
                tmpObj = iterator.next();
                if (tmpObj instanceof IBean || tmpObj instanceof List) {
                    toElem(tmpElem, key, tmpObj);
                } else {
                    tmpElem.setText(tmpObj.toString());
                }
            }
        } else {
            elemInst.addAttribute(key, obj.toString());
        }
    }

    /**
     * 测试入口
     * @param args 参数列表<br>
     *            <code>
     * &lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>
     * &lt;leopard&gt;<br>
     *     &lt;DataSource id="leopard" name="应用数据源"&gt;hd/jdbc &lt;/DataSource&gt;<br>
     *     &lt;DataSource id="version" name="版本数据源"&gt;version/jdbc &lt;/DataSource&gt;<br>
     * &lt;/leopard&gt;<br>
     * </code>
     */
    public static void main(String[] args) {
        SAXReader saxRInst = new SAXReader();
        Document docInst = null;
        try {
            docInst = saxRInst.read(new File(
                "D:\\work\\workspace\\Leopard6\\src\\com\\hd\\core\\BeanText.xml"));
            IBean beanInst = XMLUtils.toBean4Xml(docInst.getRootElement());
            System.out.println(XMLUtils.toXML4Bean(beanInst).asXML());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}

xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<leopard>
	<!-- 产品线编码 -->
	<config-item>
        <item-name>productLineCode</item-name>
        <item-value>LEOPARD</item-value>
    </config-item>
    <!--缓存类型-->
    <cache-type>1</cache-type>
    <!--数据源-->
  <!--  <datasource>
    	<application description="应用数据源">
    		<item id="appDS" default="true">jdbc/oracle</item>
    	</application>
    	<version description="版本数据源">
    		<item id="appVersionDS" >jdbc/version</item>
    	</version>
    </datasource>-->

	<datasource id="appDS" name="Oracle 服务数据源" default="true" >jdbc/oracle</datasource>
<!-- 	<datasource id="appServerDS" name="MySql 服务数据源" default="true" >jdbc/mySql</datasource> -->
	<!-- 
	<datasource id="appVersionDS" name="版本服务数据源">jdbc/version</datasource>
    -->
</leopard>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wespten

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值