Python xml.sax.saxutils.quoteattr() Examples

The following are 30 code examples of xml.sax.saxutils.quoteattr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.sax.saxutils , or try the search function .
Example #1
Source File: activecli.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def _display_xml_table_elem(doc, first=False, name=None, out=sys.stdout):
    if first:
        assert name is None
    name = '' if name is None else ' key=%s' % saxutils.quoteattr(name)
    if isinstance(doc, list):
        if not first:
            out.write('<table%s>\n' % name)
        for subdoc in doc:
            _display_xml_table_elem(subdoc, out=out)
        if not first:
            out.write('</table>\n')
    elif isinstance(doc, dict):
        if not first:
            out.write('<table%s>\n' % name)
        for key, subdoc in viewitems(doc):
            _display_xml_table_elem(subdoc, name=key, out=out)
        if not first:
            out.write('</table>\n')
    else:
        out.write('<elem%s>%s</elem>\n' % (name,
                                           saxutils.escape(
                                               str(doc),
                                               entities={'\n': '&#10;'},
                                           ))) 
Example #2
Source File: create.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 6 votes vote down vote up
def update_file(filename, items):
    '''Edits the given file in place, replacing any instances of {key} with the
    appropriate value from the provided items dict. If the given filename ends
    with ".xml" values will be quoted and escaped for XML.
    '''
    # TODO: Implement something in the templates to denote whether the value
    # being replaced is an XML attribute or a value. Perhaps move to dyanmic
    # XML tree building rather than string replacement.
    should_escape = filename.endswith('addon.xml')

    with open(filename, 'r') as inp:
        text = inp.read()

    for key, val in items.items():
        if should_escape:
            val = saxutils.quoteattr(val)
        text = text.replace('{%s}' % key, val)
    output = text

    with open(filename, 'w') as out:
        out.write(output) 
Example #3
Source File: xxsdefense.py    From darkc0de-old-stuff with GNU General Public License v3.0 6 votes vote down vote up
def handle_starttag(self, tag, method, attrs):
        if tag not in self.permitted_tags:
            self.result += xssescape("<%s>" %  tag)
        else:
            bt = "<" + tag
            if tag in self.allowed_attributes:
                attrs = dict(attrs)
                self.allowed_attributes_here = \
                  [x for x in self.allowed_attributes[tag] if x in attrs \
                   and len(attrs[x]) > 0]
                for attribute in self.allowed_attributes_here:
                    if attribute in ['href', 'src', 'background']:
                        if self.url_is_acceptable(attrs[attribute]):
                            bt += ' %s="%s"' % (attribute, attrs[attribute])
                    else:
                        bt += ' %s=%s' % \
                           (xssescape(attribute), quoteattr(attrs[attribute]))
            if bt == "<a" or bt == "<img":
                return
            if tag in self.requires_no_close:
                bt += "/"
            bt += ">"                     
            self.result += bt
            self.open_tags.insert(0, tag) 
Example #4
Source File: tv_grab_channel.py    From tvgrabpyAPI with GNU General Public License v3.0 6 votes vote down vote up
def add_starttag(self, tag, ident = 0, attribs = '', text = '', close = False):
        '''
        Add a starttag with optional attributestring, textstring and optionally close it.
        Give it the proper ident.
        '''
        if isinstance(attribs, dict):
            a = ''
            for k, v in attribs.items():
                a = '%s %s=%s' % (a, k, saxutils.quoteattr(v))

            attribs = a

        if attribs != '':
            attribs = ' %s' % attribs

        if close and text == '':
            return u'%s<%s%s/>\n' % (''.rjust(ident), self.xmlescape(tag), attribs)

        if close and text != '':
            return u'%s<%s%s>%s</%s>\n' % (''.rjust(ident), self.xmlescape(tag), attribs, self.xmlescape(text), self.xmlescape(tag))

        else:
            return u'%s<%s%s>%s\n' % (''.rjust(ident), self.xmlescape(tag), attribs, self.xmlescape(text)) 
Example #5
Source File: connection.py    From youtrack with MIT License 6 votes vote down vote up
def import_users(self, users):
        """ Import users, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Users)
            Example: importUsers([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
                                  {'login':'maxim', 'fullName':'maxim', 'email':'aaa@ss.com', 'jabber':'www@fff.com'}])
        """
        if len(users) <= 0:
            return

        known_attrs = ('login', 'fullName', 'email', 'jabber')

        xml = '<list>\n'
        for u in users:
            xml += '  <user ' + "".join(k + '=' + quoteattr(u[k]) + ' ' for k in u if k in known_attrs) + '/>\n'
        xml += '</list>'
        # TODO: convert response xml into python objects
        if isinstance(xml, str):
            xml = xml.encode('utf-8')
        return self._req_xml('PUT', '/import/users', xml, 400).toxml() 
Example #6
Source File: xml.py    From blender2ogre with GNU Lesser General Public License v2.1 6 votes vote down vote up
def toprettyxml(self, lines, indent ):
        s = '<%s ' % self.tagName
        sortedNames = sorted( self.attributes.keys() )
        for name in sortedNames:
            value = self.attributes[name]
            if not isinstance(value, str):
                value = str(value)
            s += '%s=%s ' % (name, quoteattr(value))
        if not self.childNodes:
            s += '/>'; lines.append( ('  '*indent)+s )
        else:
            s += '>'; lines.append( ('  '*indent)+s )
            indent += 1
            for child in self.childNodes:
                child.toprettyxml( lines, indent )
            indent -= 1
            lines.append(('  '*indent) + '</%s>' % self.tagName ) 
Example #7
Source File: xml.py    From blender2ogre with GNU Lesser General Public License v2.1 6 votes vote down vote up
def _out_tag(self, name, attrs, isLeaf):
        # sorted attributes -- don't want attributes output in random order, which is what the XMLGenerator class does
        self.output.write(" " * self.indent)
        self.output.write("<%s" % name)
        sortedNames = sorted( attrs.keys() )  # sorted list of attribute names
        for name in sortedNames:
            value = attrs[ name ]
            # if not of type string,
            if not isinstance(value, str):
                # turn it into a string
                value = str(value)
            self.output.write(" %s=%s" % (name, quoteattr(value)))
        if isLeaf:
            self.output.write("/")
        else:
            self.indent += 4
        self.output.write(">\n") 
Example #8
Source File: fontfinder.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def getFamilyXmlReport(self):
        """Reports on all families found as XML.
        """
        lines = []
        lines.append('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>')
        lines.append("<font_families>")
        for dirName in self._dirs:
            lines.append("    <directory name=%s/>" % quoteattr(dirName))
        for familyName in self.getFamilyNames():
            if familyName:  #skip null case
                lines.append('    <family name=%s>' % quoteattr(familyName))
                for font in self.getFontsInFamily(familyName):
                    lines.append('        ' + font.getTag())
                lines.append('    </family>')
        lines.append("</font_families>")
        return '\n'.join(lines) 
Example #9
Source File: connection.py    From youtrack with MIT License 6 votes vote down vote up
def import_work_items(self, issue_id, work_items):
        xml = ''
        for work_item in work_items:
            xml += '<workItem>'
            xml += '<date>%s</date>' % work_item.date
            xml += '<duration>%s</duration>' % work_item.duration
            if hasattr(work_item, 'description') and work_item.description is not None:
                xml += '<description>%s</description>' % escape(work_item.description)
            if hasattr(work_item, 'worktype') and work_item.worktype is not None:
                xml += '<worktype><name>%s</name></worktype>' % work_item.worktype
            xml += '<author login=%s></author>' % quoteattr(work_item.authorLogin)
            xml += '</workItem>'
        if isinstance(xml, str):
            xml = xml.encode('utf-8')
        if xml:
            xml = '<workItems>' + xml + '</workItems>'
            self._req_xml('PUT',
                          '/import/issue/%s/workitems' % urlquote(issue_id), xml) 
Example #10
Source File: xxsdefense.py    From d4rkc0de with GNU General Public License v2.0 6 votes vote down vote up
def handle_starttag(self, tag, method, attrs):
        if tag not in self.permitted_tags:
            self.result += xssescape("<%s>" %  tag)
        else:
            bt = "<" + tag
            if tag in self.allowed_attributes:
                attrs = dict(attrs)
                self.allowed_attributes_here = \
                  [x for x in self.allowed_attributes[tag] if x in attrs \
                   and len(attrs[x]) > 0]
                for attribute in self.allowed_attributes_here:
                    if attribute in ['href', 'src', 'background']:
                        if self.url_is_acceptable(attrs[attribute]):
                            bt += ' %s="%s"' % (attribute, attrs[attribute])
                    else:
                        bt += ' %s=%s' % \
                           (xssescape(attribute), quoteattr(attrs[attribute]))
            if bt == "<a" or bt == "<img":
                return
            if tag in self.requires_no_close:
                bt += "/"
            bt += ">"                     
            self.result += bt
            self.open_tags.insert(0, tag) 
Example #11
Source File: recipe-526626.py    From code with MIT License 6 votes vote down vote up
def encode(self, *args):
        if len(args) > 2:
            raise TypeError("too much arguments for encode()")
        elif not args:
            encoding = getdefaultencoding()
        else:
            encoding = args[0]

        if not self.startswith("<?xml"):
            body = self
        else:
            try:
                i = self.index("?>")
            except ValueError:
                raise ValueError("unproper XML declaration")
            body = self[i + 2:].lstrip()

        decl = '<?xml version="1.0" encoding=%s?>\n' % quoteattr(encoding)
        return decl + unicode(body).encode(*args) 
Example #12
Source File: xrc_codegen.py    From wxGlade with MIT License 6 votes vote down vote up
def write(self, output, ntabs):
        obj = self.obj

        tabs = self.tabs(ntabs)
        tabs1 = self.tabs(ntabs + 1)

        if obj is None or obj.name == "spacer":
            output.append( tabs + '<object class="spacer">\n' )
        else:
            output.append( tabs + '<object class="spacer" name=%s>\n'%quoteattr(obj.name) )
        if obj is not None:
            # a real spacer
            output.append( tabs1 + '<size>%s, %s</size>\n' % (obj.width, obj.height) )
            if obj.proportion:
                output.append(tabs1 + '<option>%s</option>\n' % obj.proportion)
            if obj.flag:
                flag = obj.properties["flag"].get_string_value()
                output.append(tabs1 + '<flag>%s</flag>\n' % self.cn_f(flag))
            if obj.border:
                output.append(tabs1 + '<border>%s</border>\n' % obj.border)
        else:
            # just an empty sizer slot
            output.append( tabs1 + '<size>0, 0</size>\n' )
        output.append(tabs + '</object>\n') 
Example #13
Source File: fontfinder.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def getFamilyXmlReport(self):
        """Reports on all families found as XML.
        """
        lines = []
        lines.append('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>')
        lines.append("<font_families>")
        for dirName in self._dirs:
            lines.append("    <directory name=%s/>" % quoteattr(dirName))
        for familyName in self.getFamilyNames():
            if familyName:  #skip null case
                lines.append('    <family name=%s>' % quoteattr(familyName))
                for font in self.getFontsInFamily(familyName):
                    lines.append('        ' + font.getTag())
                lines.append('    </family>')
        lines.append("</font_families>")
        return '\n'.join(lines) 
Example #14
Source File: create.py    From kodiswift with GNU General Public License v3.0 6 votes vote down vote up
def update_file(filename, items):
    """Edits the given file in place, replacing any instances of {key} with the
    appropriate value from the provided items dict. If the given filename ends
    with ".xml" values will be quoted and escaped for XML.
    """
    # TODO: Implement something in the templates to denote whether the value
    # being replaced is an XML attribute or a value. Perhaps move to dyanmic
    # XML tree building rather than string replacement.
    should_escape = filename.endswith('addon.xml')

    with open(filename, 'r') as inp:
        text = inp.read()

    for key, val in items.items():
        if should_escape:
            val = saxutils.quoteattr(val)
        text = text.replace('{%s}' % key, val)
    output = text

    with open(filename, 'w') as out:
        out.write(output) 
Example #15
Source File: TreeItem.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def WriteXmlString(self, streamWriter, indent=""):
        attr, text = self.GetData()
        attribStrs = "".join(
            ' %s=%s' % (k, quoteattr(unicode(v)).encode("UTF-8"))
            for k, v in attr
        )
        streamWriter("%s<%s%s" % (indent, self.xmlTag, attribStrs))
        if not text and len(self.childs) == 0:
            streamWriter(" />\r\n")
        else:
            streamWriter(">\r\n")
            newIndent = indent + "    "
            if text is not None:
                streamWriter(newIndent + escape(text).encode("UTF-8"))
                streamWriter("\r\n")
            self.WriteXmlChilds(streamWriter, newIndent)
            streamWriter(indent + "</%s>\r\n" % self.xmlTag) 
Example #16
Source File: Builtin.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def UpdateXML(doc):
    """
    Add to the mdsd XML the minimal set of OMI queries which will retrieve the metrics requested via AddMetric(). This
    provider doesn't need any configuration external to mdsd; if it did, that would be generated here as well.

    :param doc: XML document object to be updated
    :return: None
    """
    global _metrics, _eventNames, _omiClassName
    for group in _metrics:
        (class_name, condition_clause, sample_rate) = group
        if not condition_clause:
            condition_clause = default_condition(class_name)
        columns = []
        mappings = []
        for metric in _metrics[group]:
            omi_name = metric.counter_name()
            scale = _scaling[class_name][omi_name]
            columns.append(omi_name)
            mappings.append('<MapName name="{0}" {1}>{2}</MapName>'.format(omi_name, scale, metric.label()))
        column_string = ','.join(columns)
        if condition_clause:
            cql_query = quoteattr("SELECT {0} FROM {1} WHERE {2}".format(column_string,
                                                                         _omiClassName[class_name], condition_clause))
        else:
            cql_query = quoteattr("SELECT {0} FROM {1}".format(column_string, _omiClassName[class_name]))
        query = '''
<OMIQuery cqlQuery={qry} eventName={evname} omiNamespace="root/scx" sampleRateInSeconds="{rate}" storeType="local">
  <Unpivot columnName="CounterName" columnValue="Value" columns={columns}>
    {mappings}
  </Unpivot>
</OMIQuery>'''.format(
            qry=cql_query,
            evname=quoteattr(_eventNames[group]),
            columns=quoteattr(column_string),
            rate=sample_rate,
            mappings='\n    '.join(mappings)
        )
        XmlUtil.addElement(doc, 'Events/OMI', ET.fromstring(query))
    return 
Example #17
Source File: xmppserializer.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _make_ns_declarations(declarations, declared_prefixes):
        """Build namespace declarations and remove obsoleted mappings
        from `declared_prefixes`.

        :Parameters:
            - `declarations`: namespace to prefix mapping of the new
              declarations
            - `declared_prefixes`: namespace to prefix mapping of already
              declared prefixes.
        :Types:
            - `declarations`: `str` to `str` dictionary
            - `declared_prefixes`: `str` to `str` dictionary

        :Return: string of namespace declarations to be used in a start tag
        :Returntype: `str`
        """
        result = []
        for namespace, prefix in list(declarations.items()):
            if prefix:
                result.append(' xmlns:{0}={1}'.format(prefix, quoteattr(
                                                                namespace)))
            else:
                result.append(' xmlns={1}'.format(prefix, quoteattr(
                                                                namespace)))
            for d_namespace, d_prefix in list(declared_prefixes.items()):
                if (not prefix and not d_prefix) or d_prefix == prefix:
                    if namespace != d_namespace:
                        del declared_prefixes[d_namespace]
        return " ".join(result) 
Example #18
Source File: datastore_entities.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _KindPropertiesToXml(self):
    """ Convert the properties that are part of this gd kind to XML. For
    testability, the XML elements in the output are sorted alphabetically
    by property name.

    Returns:
    string  # the XML representation of the gd kind properties
    """
    properties = self._kind_properties.intersection(set(self.keys()))

    xml = u''
    for prop in sorted(properties):
      prop_xml = saxutils.quoteattr(prop)[1:-1]

      value = self[prop]
      has_toxml = (hasattr(value, 'ToXml') or
                   isinstance(value, list) and hasattr(value[0], 'ToXml'))

      for val in self._XmlEscapeValues(prop):


        if has_toxml:
          xml += '\n  %s' % val
        else:
          xml += '\n  <%s>%s</%s>' % (prop_xml, val, prop_xml)

    return xml 
Example #19
Source File: junit_xml.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def write_xml(self, stream):
        stream.write('  <testcase name="%s" time="%.3f"' % (self.name,
                                                            self.took))

        if not self.type:
            # test was successful
            stream.write('/>\n')
            return

        stream.write('>\n    <%s type="%s" message=%s><![CDATA[%s]]></%s>\n' %
                     (self.type, self.exc_name, saxutils.quoteattr(self.message),
                      escape_cdata(self.traceback), self.type))
        stream.write('  </testcase>\n') 
Example #20
Source File: junit_xml.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def write_xml(self, stream):
        stream.write('  <testcase name="%s" time="%.3f"' % (self.name,
                                                            self.took))

        if not self.type:
            # test was successful
            stream.write('/>\n')
            return

        stream.write('>\n    <%s type="%s" message=%s><![CDATA[%s]]></%s>\n' %
                     (self.type, self.exc_name, saxutils.quoteattr(self.message),
                      escape_cdata(self.traceback), self.type))
        stream.write('  </testcase>\n') 
Example #21
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def str_target(self):
    return ' '.join('%s=%s' % (k, xmlquoteattr(str(v))) for k, v in self.target.items()) 
Example #22
Source File: core.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __add(self, lst, fields):
        lst.append(u'<doc>')
        for field, value in fields.items():
            # Handle multi-valued fields if values
            # is passed in as a list/tuple
            if not isinstance(value, (list, tuple, set)):
                values = [value]
            else:
                values = value

            for value in values:
                # ignore values that are not defined
                if value == None:
                    continue
                # Do some basic data conversion
                if isinstance(value, datetime.datetime):
                    value = utc_to_string(value)
                elif isinstance(value, datetime.date):
                    value = datetime.datetime.combine(
                        value, datetime.time(tzinfo=UTC()))
                    value = utc_to_string(value)
                elif isinstance(value, bool):
                    value = value and 'true' or 'false'

                lst.append('<field name=%s>%s</field>' % (
                    (quoteattr(field),
                    escape(unicode(value)))))
        lst.append('</doc>') 
Example #23
Source File: extensionutils.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def to_xml(self):
        str_event_id = u'<Event id="{0}"/>'.format(self.eventId)
        str_provider_id = u'<Provider id="{0}"/>'.format(self.providerId)
        str_record_format = u'<Param Name="{0}" Value="{1}" T="{2}" />'
        str_record_no_quote_format = u'<Param Name="{0}" Value={1} T="{2}" />'
        str_mt_str = u'mt:wstr'
        str_mt_u_int64 = u'mt:uint64'
        str_mt_bool = u'mt:bool'
        str_mt_float = u'mt:float64'
        str_events_data = u""

        for attName in self.__dict__:
            if attName in ["eventId", "filedCount", "providerId"]:
                continue

            att_value = self.__dict__[attName]
            if type(att_value) is int:
                str_events_data += str_record_format.format(attName, att_value, str_mt_u_int64)
                continue
            if type(att_value) is str:
                att_value = xml_utils.quoteattr(att_value)
                str_events_data += str_record_no_quote_format.format(attName, att_value, str_mt_str)
                continue
            if str(type(att_value)).count("'unicode'") > 0:
                att_value = xml_utils.quoteattr(att_value)
                str_events_data += str_record_no_quote_format.format(attName, att_value, str_mt_str)
                continue
            if type(att_value) is bool:
                str_events_data += str_record_format.format(attName, att_value, str_mt_bool)
                continue
            if type(att_value) is float:
                str_events_data += str_record_format.format(attName, att_value, str_mt_float)
                continue

            logger.log(
                "Warning: property " + attName + ":" + str(type(att_value)) + ":type" +
                str(type(att_value)) + "Can't convert to events data:" + ":type not supported")

        return u"<Data>{0}{1}{2}</Data>".format(str_provider_id, str_event_id, str_events_data) 
Example #24
Source File: extensionutils.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def to_xml(self):
        str_event_id = u'<Event id="{0}"/>'.format(self.eventId)
        str_provider_id = u'<Provider id="{0}"/>'.format(self.providerId)
        str_record_format = u'<Param Name="{0}" Value="{1}" T="{2}" />'
        str_record_no_quote_format = u'<Param Name="{0}" Value={1} T="{2}" />'
        str_mt_str = u'mt:wstr'
        str_mt_u_int64 = u'mt:uint64'
        str_mt_bool = u'mt:bool'
        str_mt_float = u'mt:float64'
        str_events_data = u""

        for attName in self.__dict__:
            if attName in ["eventId", "filedCount", "providerId"]:
                continue

            att_value = self.__dict__[attName]
            if type(att_value) is int:
                str_events_data += str_record_format.format(attName, att_value, str_mt_u_int64)
                continue
            if type(att_value) is str:
                att_value = xml_utils.quoteattr(att_value)
                str_events_data += str_record_no_quote_format.format(attName, att_value, str_mt_str)
                continue
            if str(type(att_value)).count("'unicode'") > 0:
                att_value = xml_utils.quoteattr(att_value)
                str_events_data += str_record_no_quote_format.format(attName, att_value, str_mt_str)
                continue
            if type(att_value) is bool:
                str_events_data += str_record_format.format(attName, att_value, str_mt_bool)
                continue
            if type(att_value) is float:
                str_events_data += str_record_format.format(attName, att_value, str_mt_float)
                continue

            logger.log(
                "Warning: property " + attName + ":" + str(type(att_value)) + ":type" +
                str(type(att_value)) + "Can't convert to events data:" + ":type not supported")

        return u"<Data>{0}{1}{2}</Data>".format(str_provider_id, str_event_id, str_events_data) 
Example #25
Source File: odf2xhtml.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def opentag(self, tag, attrs={}, block=False):
        """ Create an open HTML tag """
        self.htmlstack.append((tag,attrs,block))
        a = []
        for key,val in attrs.items():
            a.append('''%s=%s''' % (key, quoteattr(val)))
        if len(a) == 0:
            self.writeout("<%s>" % tag)
        else:
            self.writeout("<%s %s>" % (tag, " ".join(a)))
        if block == True:
            self.writeout("\n") 
Example #26
Source File: connection.py    From youtrack with MIT License 5 votes vote down vote up
def import_links(self, links):
        """ Import links, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Links)
            Accepts result of getLinks()
            Example: importLinks([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
                                  {'login':'maxim', 'fullName':'maxim', 'email':'aaa@ss.com', 'jabber':'www@fff.com'}])
        """
        xml = '<list>\n'
        for l in links:
            # ignore typeOutward and typeInward returned by getLinks()
            xml += '  <link ' + "".join(attr + '=' + quoteattr(l[attr]) +
                                        ' ' for attr in l if attr not in ['typeInward', 'typeOutward']) + '/>\n'
        xml += '</list>'
        # TODO: convert response xml into python objects
        res = self._req_xml('PUT', '/import/links', xml, 400)
        return res.toxml() if hasattr(res, "toxml") else res 
Example #27
Source File: odf2xhtml.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def emptytag(self, tag, attrs={}):
        a = []
        for key,val in attrs.items():
            a.append('''%s=%s''' % (key, quoteattr(val)))
        self.writeout("<%s %s/>\n" % (tag, " ".join(a)))

#--------------------------------------------------
# Interface to parser
#-------------------------------------------------- 
Example #28
Source File: odf2xhtml.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def opentag(self, tag, attrs={}, block=False):
        """ Create an open HTML tag """
        self.htmlstack.append((tag,attrs,block))
        a = []
        for key,val in attrs.items():
            a.append('''%s=%s''' % (key, quoteattr(val)))
        if len(a) == 0:
            self.writeout("<%s>" % tag)
        else:
            self.writeout("<%s %s>" % (tag, " ".join(a)))
        if block == True:
            self.writeout("\n") 
Example #29
Source File: common.py    From wxGlade with MIT License 5 votes vote down vote up
def format_xml_attrs(**kwargs):
    """Format the given keyword arguments to use as XML attributes.
    The arguments will be escaped and quoted.

    The returned Unicode string doesn't contain leading and tailing spaces.

    Example::
        >>> common.format_xml_attrs(base='EditFrame', name='Frame_1')
        u'base="EditFrame" name="Frame1"'

    kwargs: Attributes to process

    Returns processed and joined kwargs as unicode"""
    if not kwargs:
        return u''

    attr_list = []
    for name in sorted(kwargs):
        value = encode_to_unicode(kwargs[name])
        value = quoteattr(value)
        value = value.strip()
        attr_list.append(u'%s=%s' % (name, value))

    attr_list.sort()
    res = u' '.join(attr_list)
    res = res.strip()
    return res 
Example #30
Source File: odf2xhtml.py    From lambda-text-extractor with Apache License 2.0 5 votes vote down vote up
def e_dc_metatag(self, tag, attrs):
        """ Any other meta data is added as a <meta> element
        """
        self.metatags.append('<meta name="%s" content=%s/>\n' % (tag[1], quoteattr(''.join(self.data))))
        self.data = []