# -*- coding: utf-8 -*-

# Copyright (c) 2004 - 2005 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a base class for all of eric3s XML writers.
"""

import os

class XMLWriterBase:
    """
    Class implementing a base class for all of eric3s XML writers.
    """
    def __init__(self, file):
        """
        Constructor
        
        @param file open file (like) object for writing
        """
        self.pf = file
        
    def _write(self, s, newline=1):
        """
        Protected method used to do the real write operation.
        
        @param s string to be written to the XML file
        @param newline flag indicating a linebreak
        """
        self.pf.write("%s%s" % (s.encode('utf-8'), 
            newline and os.linesep or ""))
        
    def writeXML(self):
        """
        Public method to write the XML to the file.
        """
        # write the XML header
        self._write('<?xml version="1.0" encoding="UTF-8"?>')
    
    def escape(self, data, attribute=0):
        """
        Function to escape &, <, and > in a string of data.
        
        @param data data to be escaped (string)
        @param attribute flag indicating escaping is done for an attribute
        @return the escaped data (string)
        """
    
        # must do ampersand first
        data = data.replace("&", "&amp;")
        data = data.replace(">", "&gt;")
        data = data.replace("<", "&lt;")
        if attribute:
            data = data.replace('"', "&quot;")
        return data
    
