# MWDOM XHTMLWriter
# Copyright (c)2001, MoonWolf. All right reserved.
require "mwdom/visitor/xmlwriter"

module MWDOM
    
  class XHTMLWriter < XMLWriter
    EMPTY=Hash.new
    %w(area base basefont br col frame hr img input isindex link meta param).each {|name|
      EMPTY[name]=true
    }
    
    def initialize(out)
      @out = out
      @ns  = nil
      @defaultns = nil
      
      @out << "<?xml version=\"1.0\"?>"
    end
    
    def visit_Element(node)
      namespaceURI = node.namespaceURI
      attr = ""
      #タグ名
      if namespaceURI==@defaultns
        name = node.localName
      else
        name = @ns[namespaceURI] + ":" + node.localName
      end
      #
      @out << "<#{name}"
      #属性
      c = node.attributes
      i = 0
      j = c.length
      while i<j
        n=c.item(i)
        
        #属性名
        if ns=n.namespaceURI
          attrname = @ns[ns] + ":" + n.localName
        else
          attrname = n.localName
        end
        @out << " " + attrname + '="'
        
        #属性値
        v = n.childNodes
        vi = 0
        vj = v.length
        while vi<vj
          visit(v.item(vi))
          vi += 1
        end
        
        @out << '"'
        i += 1
      end
      if namespaceURI=="http://www.w3.org/1999/xhtml" and EMPTY[node.localName]
        @out << " />"
      else
        @out << ">"
        visit_childNodes(node)
        @out << "</#{name}>"
      end
    end
  end
end

