dom4j心得

来源:互联网 发布:美工助理一般工资多少 编辑:程序博客网 时间:2024/04/28 02:40
主要涉及的文件和类
1、form-size.xml
2、common.model.form.FormDefine  是form-size.xml对应的类
3、common.parse.FormDefineParse  是from-size.xml对应的解析器接口
4、common.parse.dom4j.FormDefineParseImpl 是form-size.xml对应的用dom4j的解析器实例

如下是form-size.xml的内容
<?xml version="1.0" encoding="UTF-8" ?>
<form name="size" title="尺码档案">
 <data>
  <pojo>com.yangfansoft.erp.basemanage.pojo.Size</pojo>
 </data>
</form>


解析步骤
1、先获得form这个根元素
  SAXReader reader = new SAXReader();
  Element xmlConfigureRoot = null;
  try {
   return reader.read(new File(fileName)).getRootElement();
  } catch (DocumentException e) {
   e.printStackTrace();
   throw(new BaseParseException("SAXReader Exception"));
  }
2、根据根元素,获取根元素的attribute  name
   xmlDefineRoot.attributeValue("name")
3、也可以根据根元素,获取嵌套的子元素,如data
   xmlElement = (Element)xmlDefineRoot.selectSingleNode("data");
4、如果要获得pojo元素,那么只有根据data元素来获取它的子元素
   xmlElement.selectSingleNode("pojo")
5、如果要获取com.yangfansoft.erp.basemanage.pojo.Size
   xmlElement.selectSingleNode("pojo").getText();

 

 

如果同样的子元素有多个,则  //设置模块列表
  List xmlModules = xmlDefineRoot.selectNodes("module");


使用 domj4 API 创建与修改 XML 文档

    dom4j 是一种解析 XML 文档的开放源代码 XML 框架。本文介绍如何使用包含在 dom4j 中的解析器创建并修改 XML 文档。

dom4j API 包含一个解析 XML 文档的工具。本文中将使用这个解析器创建一个示例 XML 文档。清单 1 显示了这个示例 XML 文档,catalog.xml。
清单 1. 示例 XML 文档(catalog.xml)


<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<!--An XML Catalog-->
<?target instruction?>
  <journal title="XML Zone"
                  publisher="IBM developerWorks">

<article level="Intermediate" date="December-2001">
 <title>Java configuration with XML Schema</title>
 <author>
     <firstname>Marcello</firstname>
     <lastname>Vitaletti</lastname>
 </author>
  </article>
  </journal>
</catalog>

然后使用同一个解析器修改 catalog.xml,清单 2 是修改后的 XML 文档,catalog-modified.xml。
清单 2. 修改后的 XML 文档(catalog-modified.xml)


<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<!--An XML catalog-->
<?target instruction?>
  <journal title="XML Zone"
                   publisher="IBM developerWorks">

<article level="Introductory" date="October-2002">
 <title>Create flexible and extensible XML schemas</title>
 <author>
     <firstname>Ayesha</firstname>
     <lastname>Malik</lastname>
 </author>
  </article>
  </journal>
</catalog>

与 W3C DOM API 相比,使用 dom4j 所包含的解析器的好处是 dom4j 拥有本地的 XPath 支持。DOM 解析器不支持使用 XPath 选择节点。

本文包括以下几个部分:

    * 预先设置
    * 创建文档
    * 修改文档

预先设置
这个解析器可以从 http://dom4j.org/ 获取。通过设置使 dom4j-1.4/dom4j-full.jar 能够在 classpath 中访问,该文件中包括 dom4j 类、XPath 引擎以及 SAX 和 DOM 接口。如果已经使用了 JAXP 解析器中包含的 SAX 和 DOM 接口,向 classpath 中增加 dom4j-1.4/dom4j.jar。dom4j.jar 包括 dom4j 类和 XPath 引擎,但是不含 SAX 与 DOM 接口。

创建文档
本节讨论使用 dom4j API 创建 XML 文档的过程,并创建示例 XML 文档 catalog.xml。

使用 import 语句导入 dom4j API 类:


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

使用 DocumentHelper 类创建一个文档实例。DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类。

 Document document = DocumentHelper.createDocument();

使用 addElement() 方法创建根元素 catalog。 addElement() 用于向 XML 文档中增加元素。

Element catalogElement = document.addElement("catalog");

在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。

 catalogElement.addComment("An XML catalog");

在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。

catalogElement.addProcessingInstruction("target","text");

在 catalog 元素中使用 addElement() 方法增加 journal 元素。

Element journalElement =  catalogElement.addElement("journal");

使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。

journalElement.addAttribute("title", "XML Zone");
         journalElement.addAttribute("publisher", "IBM developerWorks");

向 article 元素中添加 journal 元素。

Element articleElement=journalElement.addElement("article");

为 article 元素增加 level 和 date 属性。

articleElement.addAttribute("level", "Intermediate");
      articleElement.addAttribute("date", "December-2001");

向 article 元素中增加 title 元素。

Element titleElement=articleElement.addElement("title");

使用 setText() 方法设置 article 元素的文本。

titleElement.setText("Java configuration with XML Schema");

在 article 元素中增加 author 元素。

Element authorElement=articleElement.addElement("author");

在 author 元素中增加 firstname 元素并设置该元素的文本。

Element  firstNameElement=authorElement.addElement("firstname");
     firstNameElement.setText("Marcello");

在 author 元素中增加 lastname 元素并设置该元素的文本。

Element lastNameElement=authorElement.addElement("lastname");
     lastNameElement.setText("Vitaletti");

这样就向 XML 文档中增加文档类型说明:

<!DOCTYPE catalog SYSTEM "file://c:/Dtds/catalog.dtd">

如果文档要使用文档类型定义(DTD)文档验证则必须有 Doctype。

XML 声明 <?xml version="1.0" encoding="UTF-8"?> 自动添加到 XML 文档中。

清单 3 所示的例子程序 XmlDom4J.java 用于创建 XML 文档 catalog.xml。
清单 3. 生成 XML 文档 catalog.xml 的程序(XmlDom4J.java)


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.dom4j.io.OutputFormat;
import java.io.*;



public class XmlDom4J{


public void generateDocument(){
Document document = DocumentHelper.createDocument();
     Element catalogElement = document.addElement("catalog");
     catalogElement.addComment("An XML Catalog");
     catalogElement.addProcessingInstruction("target","text");
     Element journalElement =  catalogElement.addElement("journal");
     journalElement.addAttribute("title", "XML Zone");
     journalElement.addAttribute("publisher", "IBM developerWorks");


     Element articleElement=journalElement.addElement("article");
     articleElement.addAttribute("level", "Intermediate");
     articleElement.addAttribute("date", "December-2001");
     Element  titleElement=articleElement.addElement("title");
     titleElement.setText("Java configuration with XML Schema");
     Element authorElement=articleElement.addElement("author");
     Element  firstNameElement=authorElement.addElement("firstname");
     firstNameElement.setText("Marcello");
     Element lastNameElement=authorElement.addElement("lastname");
     lastNameElement.setText("Vitaletti");

     //document.addDocType("catalog",null,"file://f:/catalog.dtd");

    try{
   
    OutputFormat format = OutputFormat.createPrettyPrint();

    XMLWriter output = new XMLWriter(

new FileWriter( new File("f:/dom4j/catalog.xml") ), format);
        output.write( document );
        output.close();
      

        }
     catch(IOException e){System.out.println(e.getMessage());}
}

public static void main(String[] argv){
XmlDom4J dom4j=new XmlDom4J();
dom4j.generateDocument();
}}


这一节讨论了创建 XML 文档的过程,下一节将介绍使用 dom4j API 修改这里创建的 XML 文档。

修改文档
这一节说明如何使用 dom4j API 修改示例 XML 文档 catalog.xml。

使用 SAXReader 解析 XML 文档 catalog.xml:

SAXReader saxReader = new SAXReader();
 Document document = saxReader.read(inputXml);

SAXReader 包含在 org.dom4j.io 包中。

inputXml 是从 c:/catalog/catalog.xml 创建的 java.io.File。使用 XPath 表达式从 article 元素中获得 level 节点列表。如果 level 属性值是“Intermediate”则改为“Introductory”。

List list = document.selectNodes("//article/@level" );
      Iterator iter=list.iterator();
        while(iter.hasNext()){
            Attribute attribute=(Attribute)iter.next();
               if(attribute.getValue().equals("Intermediate"))
               attribute.setValue("Introductory");
       }

获取 article 元素列表,从 article 元素中的 title 元素得到一个迭代器,并修改 title 元素的文本。

list = document.selectNodes("//article" );
     iter=list.iterator();
   while(iter.hasNext()){
       Element element=(Element)iter.next();
      Iterator iterator=element.elementIterator("title");
   while(iterator.hasNext()){
   Element titleElement=(Element)iterator.next();
   if(titleElement.getText().equals("Java configuration with XML Schema"))
     titleElement.setText("Create flexible and extensible XML schema");

    }}

通过和 title 元素类似的过程修改 author 元素。

清单 4 所示的示例程序 Dom4JParser.java 用于把 catalog.xml 文档修改成 catalog-modified.xml 文档。
清单 4. 用于修改 catalog.xml 的程序(Dom4Jparser.java)


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Attribute;
import java.util.List;
import java.util.Iterator;
import org.dom4j.io.XMLWriter;
import java.io.*;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Dom4JParser{

 public void modifyDocument(File inputXml){

  try{
   SAXReader saxReader = new SAXReader();
   Document document = saxReader.read(inputXml);

   List list = document.selectNodes("//article/@level" );
   Iterator iter=list.iterator();
   while(iter.hasNext()){
    Attribute attribute=(Attribute)iter.next();
    if(attribute.getValue().equals("Intermediate"))
      attribute.setValue("Introductory");

       }
  
   list = document.selectNodes("//article/@date" );
   iter=list.iterator();
   while(iter.hasNext()){
    Attribute attribute=(Attribute)iter.next();
    if(attribute.getValue().equals("December-2001"))
      attribute.setValue("October-2002");

       }

   list = document.selectNodes("//article" );
   iter=list.iterator();
   while(iter.hasNext()){
    Element element=(Element)iter.next();
    Iterator iterator=element.elementIterator("title");
      while(iterator.hasNext()){
        Element titleElement=(Element)iterator.next();
        if(titleElement.getText().equals("Java configuration with XML

      Schema"))
        titleElement.setText("Create flexible and extensible XML schema");

                                          }

                                }

    list = document.selectNodes("//article/author" );
    iter=list.iterator();
     while(iter.hasNext()){
     Element element=(Element)iter.next();
     Iterator iterator=element.elementIterator("firstname");
     while(iterator.hasNext()){
      Element firstNameElement=(Element)iterator.next();
      if(firstNameElement.getText().equals("Marcello"))
      firstNameElement.setText("Ayesha");
                                     }

                              }

    list = document.selectNodes("//article/author" );
    iter=list.iterator();
     while(iter.hasNext()){
      Element element=(Element)iter.next();
      Iterator iterator=element.elementIterator("lastname");
     while(iterator.hasNext()){
      Element lastNameElement=(Element)iterator.next();
      if(lastNameElement.getText().equals("Vitaletti"))
      lastNameElement.setText("Malik");

                                  }

                               }
     XMLWriter output = new XMLWriter(
      new FileWriter( new File("f:/dom4j/catalog-modified.xml") ));
     output.write( document );
     output.close();
   }
 
  catch(DocumentException e)
                 {
                  System.out.println(e.getMessage());
                            }

  catch(IOException e){
                       System.out.println(e.getMessage());
                    }
 }

 public static void main(String[] argv){

  Dom4JParser dom4jParser=new Dom4JParser();
  dom4jParser.modifyDocument(new File("f:/dom4j/catalog.xml"));

                                        }

   }

这一节说明了如何使用 dom4j 中的解析器修改示例 XML 文档。这个解析器不使用 DTD 或者模式验证 XML 文档。如果 XML 文档需要验证,可以解释用 dom4j 与 JAXP SAX 解析器。












现在的问题是我用什么来读取配置信息?
现在流行的是dom4j和sax,我以前一直用dom4j.可是weblogic workshop自带的是sax,我又不想再引入包了,于是就是sax吧.
第一步:ConfigParser.java
/*
 * Create Date: 2005-6-13
 * Create By: 板桥里人
 * purpose:xml配置文件属性读取器
 */
package com.infoearth.report;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;

public class ConfigParser extends DefaultHandler {

    ////定义一个Properties 用来存放属性值
    private Properties props;

    private String currentSet;
    private String currentName;
    private StringBuffer currentValue = new StringBuffer();

    //构建器初始化props
    public ConfigParser() {

        this.props = new Properties();
        }

    public Properties getProps() {
        return this.props;
        }

    //定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来.
    public void startElement(String uri, String localName, String qName, Attributes attributes)
    throws SAXException {
        currentValue.delete(0, currentValue.length());
        this.currentName =qName;
        }

    //这里是将<xxx></xxx>之间的值加入到currentValue
    public void characters(char[] ch, int start, int length) throws SAXException {
        currentValue.append(ch, start, length);
        }

    //在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中
    public void endElement(String uri, String localName, String qName) throws SAXException {
        props.put(qName.toLowerCase(), currentValue.toString().trim());
        }

    }
  
 第二步:ParseXML.java
 /*
 * Create Date: 2005-6-13
 * Create By: 板桥里人 李春雷修改
 * purpose:xml配置文件属性读取器(通用),
 */
 
package com.infoearth.report;

import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.net.URL;

public class ParseXML{
    //定义一个Properties 用来存放属性值
    private Properties props;

    public Properties getProps() {
        return this.props;
        }

    public void parse(String filename) throws Exception {
        //将我们的解析器对象化
        ConfigParser handler = new ConfigParser();
        //获取SAX工厂对象
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);
        //获取SAX解析
        SAXParser parser = factory.newSAXParser();
        try{
            //将解析器和解析对象xml联系起来,开始解析
            parser.parse(filename, handler);
            //获取解析成功后的属性
            props = handler.getProps();
            }finally{
                factory=null;
                parser=null;
                handler=null;
                }
        }
    }
第三步:ReadConfigXml.java
/*
 * Create Date: 2005-6-13
 * Create By: 李春雷
 * purpose:xml配置文件属性读取器
 */

package com.infoearth.report;

import java.util.Properties;

public class ReadConfigXml
{
    private Properties props;
  
    public ReadConfigXml(String url){
  ParseXML myRead = new ParseXML();
   try {
    myRead.parse(url);
                props = new  Properties();
                props = myRead.getProps();
   } catch (Exception e) {
    e.printStackTrace();
   }    
        }
   public  String getUserName(){
        return props.getProperty("username");
        }      
   public String getPassWord(){
        return props.getProperty("password");
    }

}


ok,搞定了,读取的时候如下:
ReadConfigXml xmlread = new ReadConfigXml("reportenv.xml");
String username = xmlread.getUserName();
String password = xmlread.getPassWord();

前两个类实现了xml文档属性设置的任意读取.只要是xml的属性值,都读到了property中,你只需在property中提取就可以了.
第三个类是我针对我的xml文件写的,似乎有点多余.呵呵.其实有难言之隐.因为不想过多的改动以前的程序架构,就画蛇添
足了一下.

另外,感谢j道,感谢板桥里人.



今天早上给数据库封装类写了个配置文件,又用org.w3c.dom包写了个方法。如下:

public class ConfigurationManager

{

    private Configuration configuationContainer = new Configuration();
    private static ConfigurationManager instance = null;
    private String filePath = System.getProperty("CONFIGPATH") + File.separator + "config" + File.separator + "configuration.xml";
  
    public static synchronized ConfigurationManager getInstance()
    {
        if(instance==null)
        {
            ConfigurationManager configuration= new ConfigurationManager();
            configuration.getConfigurationFromXML();
            return configuration;
        }
        else{
            return instance;
        }
    }
  
    private void getConfigurationFromXML()
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
            File file=new File(filePath);
            FileInputStream fis=new FileInputStream(file);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(fis);
            Element root = doc.getDocumentElement();
            /**
             * 读取XML中的Configurations标签
             */                       
            configuationContainer.setConfigurationID(root.getAttribute("id"));
            configuationContainer.setConfigurationDescription(root.getAttribute("description"));  
            /**
             * 读取XML中的config标签
             */
            NodeList configList=root.getElementsByTagName("config");
            if(configList.getLength()>0)
            {
                for(int i=0;i<configList.getLength();i++)
                {
                    Config config=new Config();
                    Element configrationElement=(Element)configList.item(i);
                    config.setConfigID(configrationElement.getAttribute("id"));
                    config.setConfigDescription(configrationElement.getAttribute("description"));
                    /**
                     * 读取XML中的property标签
                     */
                    NodeList propertyList=((Element)configList.item(i)).getElementsByTagName("property");
                    for(int j=0;j<propertyList.getLength();j++)
                    {
                        Property property=new Property();
                        Element configElement=(Element)propertyList.item(j);
                        property.setPropertyName(configElement.getAttribute("name"));
                        property.setPropertyDescription(configElement.getAttribute("description"));
                        /**
                         * 读取XML中的value标签
                         */
                        NodeList valueList=configElement.getElementsByTagName("value");
                        Element propertyElement=(Element)valueList.item(0);
                        Text text=(Text)propertyElement.getFirstChild();
                        property.setPropertyValue(text.getNodeValue());
                        /**
                         * 压入property的Map
                         */
                        config.getPropertyMap().put(property.getPropertyName(),property);
                    }
                    /**
                     * 压入config的Map
                     */
                    configuationContainer.getConfigMap().put(config.getConfigID(),config);
                }
            }         
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }      
    }
  
    public Property getPropertyByID(String configID,String propertyID)
    {
        if(this.configuationContainer.getConfigMap().isEmpty())
        {
            System.out.println("["+new Timestamp(System.currentTimeMillis())+"] ConfigurationManager-getPropertyByID : Configuation为空!");
            return null;
        }      
        Config config=(Config)this.configuationContainer.getConfigMap().get(configID);
        if(config.getPropertyMap().isEmpty()){
            System.out.println("["+new Timestamp(System.currentTimeMillis())+"] ConfigurationManager-getPropertyByID : Config为空!");
            return null;
        }
        Property property=(Property)config.getPropertyMap().get(propertyID);
        return property;
    }
  
    public void destroy()
    {
        configuationContainer=null;      
        instance = null;
    }

    public static void setInstance(ConfigurationManager instance) {
        ConfigurationManager.instance = instance;
    }

}
原创粉丝点击