编写XML作为配置文件的高级操作库

来源:互联网 发布:安易数据恢复官网 编辑:程序博客网 时间:2024/05/12 00:38
还在使用XML仅作为简单读写的配置文件吗?其实XML还有更好更实用的操作…

概述


    在Java中使用XML可谓是极为简单,JDOM问世把Java与XML的关系更近了。但是JDOM提供对于XML简单的静态操作。如果把XML作为动态配置文件或者模块安装配置文件(至少在我开发的系统中作为),仅仅使用JDOM的方法就显得有点儿力不从心了,因此,我们要充分利用JDOM的优点开发出对XML文件的高级操作库。

    我们要开发什么样的操作库呢?首先,看下面的XML信息:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <config>
  3.   <dirs>
  4.     <home>/homemyuser</home>
  5.     <tmp>/homemyusertmp</tmp>
  6.     <var>/homemyuservar</var>
  7.   </dirs>
  8. </config>


    这是一个简单的配置文件,其中重复使用主目录路径信息,很麻烦不是吗?不过这里有很好的解决方案就是使用XML内部实体,如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE config [
  3.  <!ENTITY home "/home/myuser ">
  4. ]>
  5. <config>
  6.   <dirs>
  7.     <home>&home; </home>
  8.     <tmp>&home; /tmp</tmp>
  9.     <var>&home; /var</var>
  10.   </dirs>
  11. </config>


    这是个不错的办法,通过定义实体可是替换那些重复使用的信息。不过我还是要实现自己的方法,至于它们的区别,我会在下面讲述。
变量
    因为我是程序员,看到这样的问题首先会想到"变量"这个词。为什么不使用一个特殊的元素作为变量的定义呢?OK,开始让我们实现吧。请看下面的示例:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <config>
  3.   <property name="home" value="/home/myuser"/>
  4.   <dirs>
  5.     <!-这段可以省略了'
  6.     <home>${home} </home>
  7.     <property name="home" value="${home}/tmp"/>
  8.     <tmp path="${dirs.home}">
  9.       <tmp1>${dirs.home}/tmp1</tmp1>
  10.     </tmp>
  11.     <var>${home}/var</var>
  12.   </dirs>
  13. </config>


    在这里我使用了property元素作为变量的定义元素。咦?看懂了没有?有两个home变量啊,那该怎么解决冲突呢?正如上面显示的,使用 元素名称+"."+变量名称 作为该变量的定义以解决冲突如何?那就这么做吧。

    OK,配置变量规则都设计出来了该写解释器了。

因为可能以后还会增加额外的解释器,我们先定义一个解释器接口DocumentParser:

  1. import org.jdom.Document;
  2. public interface DocumentParser{
  3.   public void parse(Document doc);
  4. }


    既然接口已定义好,就该写变量解释器了。

  1. / ** 
  2. * property元素解释器。
  3. */
  4. public class DocumentPropertyParser implements DocumentParser{
  5.   private Properties variables;
  6.   public DocumentPropertyParser(){
  7.     variables = new Properties();
  8.   }
  9.   public void parse(Document doc){
  10.     Element element = doc.getRootElement();
  11.     String path = element.getName();
  12.     //解析变量并添加到variables属性对象中
  13.     parseVariables(path, element);
  14.     //分析元素属性和值, 替换已解析的变量.
  15.     parseContent(element);
  16.   }
  17.   / **
  18.    * 解析变量方法
  19.    */
  20.   private void parseVariables(String path, Element element){
  21.     List subList = element.getChildren();
  22.     Iterator elementI = subList.iterator();
  23.     while(elementI.hasNext()){
  24.       Element elementS = (Element)elementI.next();
  25.       String name = elementS.getName();
  26.       //处理变量, 这里忽略了property元素名称的大小写.
  27.       //否则, 递归处理里面的元素.
  28.       if("property".equalsIgnoreCase(name)){
  29.         //获取变量名称.
  30.         String propName = elementS.getAttributeValue("name");
  31.         //如果变量名称不为空, 则先获取名称为value的属性.
  32.         if(propName != null){
  33.           String propValue = elementS.getAttributeValue("value");
  34.           //如果名称为value的属性不存在, 则获取该元素的值.
  35.           if(propValue == null) propValue = elementS.getText();
  36.           //如果其值也不存在, 则该变量的值取空.
  37.           if(propValue == null) propValue = "";
  38.           //向变量列表中加入该变量信息.
  39.           variables.setProperty(path + "." + propName, propValue);
  40.         }
  41.         //删除属性字段, 避免冲突.
  42.         elementI.remove();
  43.       } else{
  44.         parseVariables(path + "." + name, elementS);
  45.       }
  46.     }
  47.   }
  48.   / **
  49.    * 处理元素中的变量.
  50.    */
  51.   private void parseContent(Element element){
  52.     //首先, 检查该元素属性值是否存在变量.
  53.     List attributes = element.getAttributes();
  54.     Iterator attributeI = attributes.iterator();
  55.     while(attributeI.hasNext()){
  56.       Attribute attribute = (Attribute)attributeI.next();
  57.       String attributeValue = attribute.getValue();
  58.       //使用字符串替换方法替换变量.
  59.       Enumeration propNames = variables.propertyNames();
  60.       while(propNames.hasMoreElements()){
  61.         String propName = (String)propNames.nextElement();
  62.         String propValue = variables.getProperty(propName);
  63.         attributeValue = StrUtil.replace("${" + propName + "}",
  64.                                          propValue,
  65.                                          attributeValue);
  66.       }
  67.       
  68.       //重新设置替换过的变量值.
  69.       attribute.setValue(attributeValue);
  70.     }
  71.     //如果有子信息, 递归检索子信息, 否则检索其值.
  72.     List subElements = element.getChildren();
  73.     if(subElements.size() != 0){
  74.       //递归检索Element.
  75.       Iterator subElementI = subElements.iterator();
  76.       while(subElementI.hasNext()){
  77.         Element subElement = (Element)subElementI.next();
  78.         parseContent(subElement);
  79.       }
  80.     } else{
  81.       String value = element.getText();
  82.       if(value != null){
  83.         //覆盖变量.
  84.         Enumeration propNames = variables.propertyNames();
  85.         while(propNames.hasMoreElements()){
  86.           String propName = (String)propNames.nextElement();
  87.           String propValue = variables.getProperty(propName);
  88.           value = StrUtil.replace("${" + propName + "}", propValue, value);
  89.         }
  90.         element.setText(value);
  91.       }
  92.     }
  93.   }
  94. }

注:StrUtil.replace方法是一般字符串替换方法,自行实现。

    OK,简单的变量解释器完工了。
    
    再想想还需要什么…

系统变量


    有时候,配置文件需要一些系统的信息作为参考(我称为系统变量),而系统信息是在运行期才可以得到的,不过我们可以通过预定义一些变量名称使在配置文件中可以提前使用,通过解释系统变量来动态为该元素赋值。例如这个配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <config>
  3.   <property name="version" value="1705"/>
  4.   <module version="%{system.version}.${version}" home="%{system.home}/helloword">
  5.     … …
  6.   </module>
  7. </config>


    解析后变成了:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <config>
  3.   <module version="1.0.1705" home="/home/myuser/helloworld">
  4.     … …
  5.   </module>
  6. </config>


    这里使用了我们预定义的系统变量"system.version"和"system.home"分别表示系统版本和系统的主目录。这使得配置文件具备获取系统动态信息的能力。下面我们用Java实现系统变量解释器DocumentConstantParser:

  1. public final class DocumentConstantParser implements DocumentParser{
  2.   private Properties constants;
  3.   public DocumentConstantParser(){
  4.     constants = new Properties();
  5.   }
  6.   public DocumentConstantParser(Properties original){
  7.     constants = new Properties(original);
  8.   }
  9.   //通过运行期设置预定义的变量, 配置文件可以动态读取这些信息.
  10.   public void addConstant(String name, String value){
  11.     constants.setProperty(name, value);
  12.   }
  13.   public void removeConstant(String name){
  14.     constants.remove(name);
  15.   }
  16.   public void parse(Document doc){
  17.     parseContent(doc.getRootElement());
  18.   }
  19.   …
  20. }


因为parseContent方法跟变量解释器的几乎相同,所以节省点儿空间就不写出了。系统可以通过使用addConstant和removeConstant方法操作对XML文档预定义的变量,这使得XML的配置功能更强大了。

比较前述的使用实体,此方法易于跟系统交互,且方法简便易懂。

命令


    曾经研究过Ant,其中的<javac>等元素十分吸引我。能不能再添加一个具有命令解释能力的元素呢?答案是肯定的。
    
    我定义XML文档中的command元素作为命令的入口元素。通过实现具体命令实现执行该命令。首先,因为可能有很多命令,我们定义一个命令接口DocumentCommand:

  1. public interface DocumentCommand{
  2.   //检查是否接受指定名称的命令。
  3.   public boolean accept(String name);
  4.   //处理命令
  5.   public void invoke(Document doc, Element current, DocumentCommandParser parser) 
  6. throws JDOMException;
  7. }


定义好了命令解释接口,就可以设计解释器了。Java代码如下:

  1. public final class DocumentCommandParser implements DocumentParser{
  2.   private HashSet commands;
  3.   private boolean parsing;
  4.   public DocumentCommandParser(){
  5.     commands = new HashSet(10);
  6.     parsing = false;
  7.   }
  8.   //添加命令解释单元
  9.   public synchronized void addCommand(DocumentCommand dc){
  10.     if(parsing)
  11.       try{
  12.         wait();
  13.       }catch(InterruptedException ie){}
  14.     if(commands.contains(dc))
  15.       commands.remove(dc);
  16.     commands.add(dc);
  17.   }
  18.   //删除命令解释单元
  19.   public synchronized void removeCommand(DocumentCommand dc){
  20.     if(parsing)
  21.       try{
  22.         wait();
  23.       }catch(InterruptedException ie){}
  24.     commands.remove(dc);
  25.   }
  26.   public synchronized void parse(Document doc) throws JDOMException{
  27.     parsing = true;
  28.     parseCommand(doc, doc.getRootElement());
  29.     parsing = false;
  30.     notifyAll();
  31.   }
  32.   private void parseCommand(Document doc, Element element) throws JDOMException{
  33.     List sub = element.getChildren();
  34.     for(int i = 0;i < sub.size();i++){
  35.       Element subElement = (Element)sub.get(i);
  36.       //检查该元素是否是命令元素, 如果不是递归解释该元素的子元素.
  37.       if(!"command".equalsIgnoreCase(subElement.getName())){
  38.         parseCommand(doc, subElement);
  39.       } else{
  40.         //删除命令元素, 避免冲突.
  41.         sub.remove(i--);
  42.         //获取命令名称,如果为空, 则继续.
  43.         String commandName = subElement.getAttributeValue("name");
  44.         if(commandName != null){
  45.           //开始检索适合的命令处理器.
  46.           Iterator cmdI = commands.iterator();
  47.           processing:
  48.           while(cmdI.hasNext()){
  49.             DocumentCommand dc = (DocumentCommand)cmdI.next();
  50.             //找到对应命令处理器后, 进行命令解释.
  51.             if(dc.accept(commandName)){
  52.               //调用命令处理方法, 如果执行成功, 删除该变量.
  53.               dc.invoke(doc, subElement, this);
  54.               //中断命令检索过程.
  55.               break processing;
  56.             }
  57.           }
  58.         }
  59.       }
  60.     }
  61.   }
  62. }


    终于实现了命令解释功能,下面来研究一下它的用途。
    例如,一个文件拷贝命令filecopy有两个属性,source为源文件路径,target为拷贝目的路径,通过这一命令可以实现众多功能,如组件安装时从其他空间拷贝数据到其主目录。代码如下:

  1. … …
  2.   <command name="filecopy" source="${home} /lib" target="%{system}/lib/module"/> 
  3. … …



    这样,组件所使用到的库文件就拷贝到了系统的库中。下面是filecopy的代码:

  1. public class FileCopyCommand implements com.yipsilon.util.jdom.DocumentCommand{
  2.     public boolean accept(String s){
  3.       
  4.       //只有filecopy命令可以接受.
  5.       return "filecopy".equals(s);
  6.     }
  7.     public void invoke(Document document, Element element, DocumentCommandParser parser){
  8.       String name = element.getAttributeValue("name");     //值为: filecopy
  9.       String source = element.getAttributeValue ("source"); //值为原路径
  10.       String target = element.getAttributeValue ("target"); //值为目的路径
  11.       FileUtil.copy(source, target);
  12.       //因内容有限, 这里没有增加额外的错误检查.
  13.     }
  14.   }

注:FileUtil.copy是简单的文件拷贝方法, 请自行实现。

结论


    通过在XML文档中使用变量、系统变量、命令大大增强了XML作为配置信息集合的功能。通过实现不同的解释器和命令单元,可以使其功能不断增多从而实现一些以前无法实现的目的,比如作为安装文件进行环境检测、I/O操作等,既能提高开发速度,内容也好管理。

    Java与XML与生俱来,在它们的身上可以开发出很多简化开发的产品,如Ant。有时候只需要动动脑筋就可以使开发变得简单。
原创粉丝点击