/*
 * $RCSfile: XmlElement.java,v $
 * $Date: 2006/01/26 14:48:59 $
 * $Revision: 1.1.2.2 $
 * $Author: andreys $
 */
 
/*
 * Copyright (c) 2002-2003 IST-2004-2006-511731 ModelWare - ModelBus.
 * All rights reserved.
 *
 * This software is published under the terms of the ModelBus Software License
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * A copy of ModelBus Software License is provided with this distribution in
 * doc/LICENSE.txt file.
 */
 
/*
 * XmlElementImpl.java Add description 
 * 
 * @author Prawee Sriplakich
 * @version $Revision: 1.1.2.2 $ $Date: 2006/01/26 14:48:59 $
 * @see Add references
 *
 * TODO Add description
 * TODO Add references
 */
package org.eclipse.mddi.modelbus.adapter.infrastructure.serialize.modelbus_xmi;

import java.util.Iterator;
import java.util.List;
import java.util.Vector;


/**
 * @author P. Sriplakich
 *
 *
 */
public class XmlElement  {
    
    public static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"ASCII\"?>";

    public String name;
    public String text = null;
    List properties = new Vector();
    public List children;
    
    
    public XmlElement(String name) {
      this.name = name;    
    }
    
    public void appendChild(XmlElement child) {
      if(children==null) {
        children = new Vector();    
      }
      children.add(child);
    }
    
    public void setNodeValue(String v) {
        text = v;
    }
    
    
    public void setAttribute(String a, String v) {
      for(Iterator it = properties.iterator(); it.hasNext(); ) {
        Entry e = (Entry)it.next();
        if(e.att.equals(a)) {
          e.v = v;
          return;
        }
      }
      properties.add(new Entry(a,v));
    }
    
    
    
    public String toString() {
       StringBuffer sb = new StringBuffer();
       appendTo(sb);
       return sb.toString();       
    }
    
    public void appendTo(StringBuffer sb) {             
      sb.append("<" +name);
      
      for(Iterator it=properties.iterator(); it.hasNext();  ) {
         Entry e = (Entry) it.next();
         sb.append(" " +e.att +"=\"" +e.v +"\"");
      }      
      
      if(children==null && text==null) {
        sb.append("/>");
      } else {
        sb.append(">");
        if(children!=null) {
          //int count = 0;  
          for(Iterator it = children.iterator(); it.hasNext(); ) {
           ((XmlElement) it.next()).appendTo(sb);
           //System.out.println(count++);           
          }
        } 
        if(text!=null) {
          sb.append(text);    
        }
        sb.append("</" +name +">");
      }
    }
  
    static class Entry {
      String att;
      String v;
      Entry(String a, String v) {
        this.att = a;
        this.v = v;
      }
    }
    
}
