dom4j操作 xml文件

父类:

public  class BaseXMLConfig {
    public static final Logger logger = LogManager.getLogger(BaseXMLConfig.class);

    public static void store(Document doc,File xmlConfig) throws IOException{
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        FileOutputStream fos=new FileOutputStream(xmlConfig);
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        fos.close();
        writer.close();
        logger.info(xmlConfig.getAbsolutePath()+" store success.");
    }
    //
    public static void initConfig(String rootElement,File xmlConfig)throws Exception{
         Document doc = DocumentHelper.createDocument();
         doc.addElement(rootElement);
         OutputFormat format = OutputFormat.createPrettyPrint();
         format.setEncoding("utf-8");
         File dir=new File(xmlConfig.getParent());
         if (!dir.exists()) {
             dir.mkdirs();
        }
         FileOutputStream fos=new FileOutputStream(xmlConfig);
         XMLWriter writer = new XMLWriter(fos, format);
         writer.write(doc);
         fos.close();
         writer.close();
    }
    /**
     * 获取节点下子节点属性的值
     * @param thisE 
     * @param elementName
     * @param attrName
     * @return
     */
    public static String getInnerElementAttribute(Element thisE,String elementName,String attrName){
        Element inner=thisE.element(elementName);
        if (inner==null) {
            return null;
        }
        return inner.attributeValue(attrName);
    }
}

子类:

public class HistoryXMLConfig extends BaseXMLConfig{
    private static final String rootElement="versionRecord";
    private static File xmlConfig=new File(SysPropUtil.getConfigPath()+File.separator+"history.xml");
    //private static File xmlConfig=new File("E:\\Workspaces\\MyEclipseWS\\AutoUpdateTool\\config\\history.xml");
    private static Document document;
    static{
        try {
             // 1.创建一个SAXReader对象reader
            SAXReader reader = new SAXReader();
            // 2.通过reader对象的read方法加载xml文件,获取Document对象
            if (!xmlConfig.exists()) {
                initConfig(rootElement,xmlConfig);
            }
            document = reader.read(xmlConfig);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("init DownloadXMLConfig failed : "+e);
        }
    }

    public static void  store() throws IOException{
        store(document,xmlConfig);
    }

    //修改生效版本
    public static void updateEffectVersion(Element rversion)throws Exception{

        Element effectversion=(Element) document.getRootElement().selectSingleNode("version[@isDefault='true']");
        if (effectversion!=null) {
            effectversion.addAttribute("isDefault", "false");
        }

        rversion.addAttribute("isDefault", "true");
        store();
    }
    public static void updateEffectVersion(String rversion)throws Exception{
        Element version=(Element) document.getRootElement().selectSingleNode("version[@value='"+rversion+"']");
        updateEffectVersion(version);
    }

    //写数据
    public static void writeConfig(String rversion,String[] apps)throws Exception{
        Element version=(Element) document.getRootElement().selectSingleNode("version[@value='"+rversion+"']");
        Element applist=null;
        if (version==null) {
            version=document.getRootElement().addElement("version");
            version.addAttribute("value", rversion);
            applist=version.addElement("appList");
        }else{
            applist=version.element("appList");
        }
        for (int i = 0; i < apps.length; i++) {
            Element app=(Element) applist.selectSingleNode("app[@value='"+apps[i]+"']");
            if (app==null) {
                applist.addElement("app").addAttribute("value", apps[i]);
            }
        }
        updateEffectVersion(version);
    }

    //根据资源版本号检查本地是否存在该资源版本
    public static boolean isExistVersion(String rversion){
        if (getVersionByRnum(rversion)==null) {
            return false;
        }else{
            return true;
        }
    }
    //根据版本号获取版本节点
    public static Element getVersionByRnum(String rversion){
        Node node=document.getRootElement().selectSingleNode("version[@value='"+rversion+"']");
        return (Element) node;
    }

    //获取当前生效的版本
    public static Element getEffectVer(){
        Node node=document.getRootElement().selectSingleNode("version[@isDefault='true']");
        return (Element) node;
    }
    public static String getEffectVerString(){
        Element effectversion=getEffectVer();
        if (effectversion!=null) {
            return effectversion.attributeValue("value");
        }else{
            return null;
        }
    }

    /**
     * 获取当前生效版本的app集合
     * @return
     */
    public static String[] getEffectApps(){
        Element effectversion=getEffectVer();
        return getAppsByVersion(effectversion);
    }

    /**
     * 获取指定版本的app集合
     * @return
     */
    public static String[] getAppsByVersion(String verNum){
        Element version=getVersionByRnum(verNum);
        return getAppsByVersion(version);
    }
    public static String[] getAppsByVersion(Element verNum){
        Set<String> appset=new HashSet<String>();
        List<Node> list=verNum.selectNodes("appList/app");
        for (Node node : list) {
            appset.add(((Element) node).attributeValue("value"));
        }
        String[] arr={};
        return appset.toArray(arr);
    }
    /**
     * 根据配置文件获取本地已经下载的最新版本的app信息
     * @return
     */
    public static String[] getDownloadApp(){
        Set<String> appset=new HashSet<String>();
        Element root=document.getRootElement();
        List<Node> list=document.getRootElement().selectNodes("version/appList/app");
        for (Node node : list) {
            appset.add(((Element) node).attributeValue("value"));
        }
        String[] arr={};
        return appset.toArray(arr);
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值