我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用xml.sax.saxutils.quoteattr()。
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)
def get_view(self, wizard, state_name): template = wizard.template.template fields = {} view = { 'model': 'account.move.template.create.keywords', 'view_id': 0, 'fields': fields, } field_template = ('<label name=%(name)s/>' '<field name=%(name)s/>') view['arch'] = ('<?xml version="1.0"?>' '<form col="2" string=%s>%s</form>' % ( quoteattr(template.name), ''.join(field_template % {'name': quoteattr(keyword.name)} for keyword in template.keywords) )) for keyword in template.keywords: fields[keyword.name] = keyword.get_field() return view
def _flattenWOFFMetadataString(element, sub=False): text = element.text.strip() for subElement in element: text += _flattenWOFFMetadataString(subElement, sub=True) if element.tail: text += element.tail.strip() if sub: attrib = ["%s=%s" % (key, quoteattr(value)) for key, value in element.attrib.items()] attrib = " ".join(attrib) if attrib: start = "<%s %s>" % (element.tag, attrib) else: start = "<%s>" % (element.tag) end = "</%s>" % (element.tag) text = start + text + end return text
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 )
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")
def importWorkItems(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._reqXml('PUT', '/import/issue/%s/workitems' % urlquote(issue_id), xml)
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)
def generate_aliases_column_section(self): column_aliases_array = [] # Now to put in each column tag for column_alias in self.column_aliases: c = etree.Element(u"column") # Name is the Tableau Field Alias, always surrounded by brackets SQL Server style c.set(u"name", u"[{}]".format(column_alias)) if self.column_aliases[column_alias][u"datatype"] is not None: c.set(u"datatype", self.column_aliases[column_alias][u"datatype"]) if self.column_aliases[column_alias][u"caption"] is not None: c.set(u"caption", self.column_aliases[column_alias][u"caption"]) if self.column_aliases[column_alias][u"role"] is not None: c.set(u"role", self.column_aliases[column_alias][u"role"]) if self.column_aliases[column_alias][u"type"] is not None: c.set(u"type", self.column_aliases[column_alias][u"type"]) if self.column_aliases[column_alias][u'calculation'] is not None: calc = etree.Element(u'calculation') calc.set(u'class', u'tableau') # quoteattr adds an extra real set of quotes around the string, which needs to be sliced out calc.set(u'formula', quoteattr(self.column_aliases[column_alias][u'calculation'])[1:-1]) c.append(calc) column_aliases_array.append(c) return column_aliases_array
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)
def dump_xml(props, fp, comment=None, encoding='UTF-8', sort_keys=False): """ Write a series ``props`` of key-value pairs to a binary filehandle ``fp`` in the format of an XML properties file. The file will include both an XML declaration and a doctype declaration. :param props: A mapping or iterable of ``(key, value)`` pairs to write to ``fp``. All keys and values in ``props`` must be text strings. If ``sort_keys`` is `False`, the entries are output in iteration order. :param fp: a file-like object to write the values of ``props`` to :type fp: binary file-like object :param comment: if non-`None`, ``comment`` will be output as a ``<comment>`` element before the ``<entry>`` elements :type comment: text string or `None` :param string encoding: the name of the encoding to use for the XML document (also included in the XML declaration) :param bool sort_keys: if true, the elements of ``props`` are sorted lexicographically by key in the output :return: `None` """ fp = codecs.lookup(encoding).streamwriter(fp, errors='xmlcharrefreplace') print('<?xml version="1.0" encoding={0} standalone="no"?>' .format(quoteattr(encoding)), file=fp) for s in _stream_xml(props, comment, sort_keys): print(s, file=fp)
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))
def predicate(self, predicate, object, depth=1): write = self.write indent = " " * depth qname = self.store.namespace_manager.qname(predicate) if isinstance(object, Literal): attributes = "" if object.language: attributes += ' xml:lang="%s"' % object.language if object.datatype: attributes += ' rdf:datatype="%s"' % object.datatype write("%s<%s%s>%s</%s>\n" % (indent, qname, attributes, escape(object, ESCAPE_ENTITIES), qname)) else: if isinstance(object, BNode): write('%s<%s rdf:nodeID="%s"/>\n' % (indent, qname, object)) else: write("%s<%s rdf:resource=%s/>\n" % (indent, qname, quoteattr(self.relativize(object))))
def node(type_name, props): yield ( '{type_name} [shape=plaintext label=<\n' ' <table border="1" cellborder="0" cellspacing="0" align="left">\n' ' <tr><td PORT="uuid" border="1" sides="B" bgcolor="lavender" href="/profiles/{type_name}.json">{type_name}</td></tr>' ).format(type_name=type_name) items = sorted(props.items()) for name, prop in items: if name == 'uuid' or prop.get('notSubmittable'): continue label = escape(name) if 'items' in prop: label += ' []' prop = prop['items'] if 'linkTo' in prop: label = '<b>' + label + '</b>' yield ' <tr><td PORT={name}>{label}</td></tr>'.format(name=quoteattr(name), label=label) yield ' </table>>];'
def startDTD(self, name, public_id, system_id): self._out.write('<!DOCTYPE %s' % name) if public_id: self._out.write(' PUBLIC %s %s' % ( saxutils.quoteattr(public_id), saxutils.quoteattr(system_id))) elif system_id: self._out.write(' SYSTEM %s' % saxutils.quoteattr(system_id))
def _quoteattr(self, attr): """Escape an XML attribute. Value can be unicode.""" attr = xml_safe(attr) return saxutils.quoteattr(attr)
def _quoteattr(self, attr): """Escape an XML attribute. Value can be unicode.""" attr = xml_safe(attr) if isinstance(attr, unicode) and not UNICODE_STRINGS: attr = attr.encode(self.encoding) return saxutils.quoteattr(attr)
def add_dict_entry_internal(self, formatted_head_word, forms, formatted_desc): self.n_expanded_entries += 1 self.index_size += len(forms) if self.entries_in_curr_dict_html >= self.max_entries_per_dict_html: self.close_dict_html() self.start_dict_html() self.entries_in_curr_dict_html += 1 self.curr_dict_f.write(""" <idx:entry scriptable="yes" spell="yes"> <idx:short> <idx:orth value=%s>%s """ % (quoteattr(forms[0]), formatted_head_word)) if len(forms[1:]) > 0: self.curr_dict_f.write(""" <idx:infl> """) for infl in forms[1:]: self.curr_dict_f.write("""<idx:iform value=%s exact="yes"/>\n""" % quoteattr(infl)) self.curr_dict_f.write(""" </idx:infl> """) self.curr_dict_f.write(""" </idx:orth> %s </idx:short> </idx:entry> """ % formatted_desc)
def write_dict(self, dictionary): """Write one record for the specified entity.""" if self.xml_style == self.ELEMENT_CENTRIC: self.output_stream.write('%s<%s>\n' % (self.indent, self.entity_node)) self.write_iterable_as_elements(dictionary) self.output_stream.write('%s</%s>\n' % (self.indent, self.entity_node)) else: self.output_stream.write('%s<%s ' % (self.indent, self.entity_node)) for (name, value) in dictionary.iteritems(): self.output_stream.write('%s=%s ' % (name, saxutils.quoteattr(value))) self.output_stream.write('/>\n')
def ToXml(self): return u'<category term="%s" label=%s />' % (Category.TERM, saxutils.quoteattr(self))
def ToXml(self): return u'<link href=%s />' % saxutils.quoteattr(self)
def ToXml(self): return u'<gd:email address=%s />' % saxutils.quoteattr(self)
def ToXml(self): return (u'<gd:im protocol=%s address=%s />' % (saxutils.quoteattr(self.protocol), saxutils.quoteattr(self.address)))
def _PropertiesToXml(self, properties): """ Returns a list of the XML representations of each of the given properties. Ignores properties that don't exist in this entity. Arg: properties: string or list of strings Returns: list of strings """ xml_properties = [] for propname in properties: if not self.has_key(propname): continue propname_xml = saxutils.quoteattr(propname) values = self[propname] if isinstance(values, list) and not values: continue if not isinstance(values, list): values = [values] proptype = datastore_types.PropertyTypeName(values[0]) proptype_xml = saxutils.quoteattr(proptype) escaped_values = self._XmlEscapeValues(propname) open_tag = u'<property name=%s type=%s>' % (propname_xml, proptype_xml) close_tag = u'</property>' xml_properties += [open_tag + val + close_tag for val in escaped_values] return xml_properties
def getTag(self): "Return an XML tag representation" attrs = [] for k, v in self.__dict__.items(): if k not in ['timeModified']: if v: attrs.append('%s=%s' % (k, quoteattr(str(v)))) return '<font ' + ' '.join(attrs) + '/>'
def _parseXml(self, settingXmlFile): try: root = ET.parse(settingXmlFile).getroot() except: # ParseError from xml.sax.saxutils import quoteattr with open(settingXmlFile, 'r') as f: content = f.read() content = re.sub(r'(?<==)(["\'])(.*?)\1', lambda x: quoteattr(x.group(2)), content) root = ET.fromstring(content) return root
def startElementNS(self, name, qname, attrs): self._write(unicode('<' + self.makeName(name))) for pair in self._undeclared_ns_maps: self._write(unicode(' xmlns:%s="%s"' % pair)) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): self._write(unicode(' %s=%s' % (self.makeName(name), quoteattr(value)))) self._write(unicode('>')) # general purpose xml writer, does a bunch of useful stuff above & beyond XmlGenerator