引言
    ECS 提供了一种编程方式来生成以不同标记语言编写的文档。它设计为通过面向对象的抽象来生成所有标签。
     ECS 目前版本为1.4.2 ,支持 HTML 4.0 和 XML 。
因为工作原因,作者粗略读了ECS的部分原代码,着重了解ECS如果通过toString方法实现HTML代码的生成。如有不足之处,请指出。
前期准备
下载Jakarta ECS http://jakarta.apache.org/ecs
开始
    ECS 将HTML的标签都做为一个JavaBean实现,放在org.apache.ecs.html下,每个元素都有相应的getter和setter方法实现对象属性的存取。并通过toString方法将元素转化为标准的html代码。
     toString方法是如何实现的呢?我们先看看ECS主要类结构:
![[代码阅读] <wbr>ECS <wbr>toString实现方法 [代码阅读] <wbr>ECS <wbr>toString实现方法](http://simg.sinajs.cn/blog7style/images/common/sg_trans.gif)
     原来任何元素都是从ConcreteElement继承过来的,而ConcreteElement又继承了ElementAttributes。 ConcreteElement实现了元素addElement方法,ElementAttributes实现了元素addAttribute的方法。
     ConcreteElement和ElementAttributes都采用了hashtable的方法存取数据。我们看看它们的关键代码:
    ConcreteElement关键代码:
    
 以下内容为程序代码:
         private Hashtable registry = new Hashtable(4); // keep a list of elements that need to be added to the element
        
         private Vector registryList = new Vector(2);
……
        
         public Element addElementToRegistry(String hashcode,Element element)
         {
             if ( hashcode == null || element == null )
                 return(this);
             element.setFilterState(getFilterState());
             if(ECSDefaults.getDefaultPrettyPrint() != element.getPrettyPrint())
                 element.setPrettyPrint(getPrettyPrint());
             registry.put(hashcode,element);
             if(!registryList.contains(hashcode))
                 registryList.addElement(hashcode);
             return(this);
         }
         ……
    
   
     ElementAttributes 和ConcreteElement不同,hashtable的声明是在超类GenericElement中实现的。
     ElementAttributes关键代码:
    
 以下内容为程序代码:
         public Element addAttribute(String s, int i)
         {
             getElementHashEntry().put(s, new Integer(i));
             return this;
         }
    
   
     GenericElement关键代码:
    
 以下内容为程序代码:
         private Hashtable element;
         ……
         public GenericElement()
         {
         ……
             element = new Hashtable(4);
             ……
         }
         ……
         protected Hashtable getElementHashEntry()
         {
             return element;
         }
    
   
     元素的toString的真正实现也在GenericElement里
    
 以下内容为程序代码:
         public final String toString()
         {
             StringWriter stringwriter = new StringWriter();
             String s = null;
             try
             {
                 output(stringwriter);
                 stringwriter.flush();
                 s = stringwriter.toString();
                 stringwriter.close();
             }
             catch(UnsupportedEncodingException unsupportedencodingexception)
             {
                 unsupportedencodingexception.printStackTrace();
             }
             catch(IOException ioexception)
             {
                 ioexception.printStackTrace();
             }
             return s;