我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用genshi.core.QName()。
def __call__(self, stream, directives, ctxt, **vars): def _generate(): kind, (tag, attrib), pos = stream.next() attrs = _eval_expr(self.expr, ctxt, vars) if attrs: if isinstance(attrs, Stream): try: attrs = iter(attrs).next() except StopIteration: attrs = [] elif not isinstance(attrs, list): # assume it's a dict attrs = attrs.items() attrib |= [ (QName(n), v is not None and unicode(v).strip() or None) for n, v in attrs ] yield kind, (tag, attrib), pos for event in stream: yield event return _apply_directives(_generate(), directives, ctxt, vars)
def select(self, path): """Mark events matching the given XPath expression, within the current selection. >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer().select('.//em').trace()) (None, ('START', (QName('body'), Attrs()), (None, 1, 0))) (None, ('TEXT', u'Some ', (None, 1, 6))) ('ENTER', ('START', (QName('em'), Attrs()), (None, 1, 11))) ('INSIDE', ('TEXT', u'test', (None, 1, 15))) ('EXIT', ('END', QName('em'), (None, 1, 19))) (None, ('TEXT', u' text', (None, 1, 24))) (None, ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :param path: an XPath expression (as string) or a `Path` instance :return: the stream augmented by transformation marks :rtype: `Transformer` """ return self.apply(SelectTransformation(path))
def invert(self): """Invert selection so that marked events become unmarked, and vice versa. Specificaly, all marks are converted to null marks, and all null marks are converted to OUTSIDE marks. >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer('//em').invert().trace()) ('OUTSIDE', ('START', (QName('body'), Attrs()), (None, 1, 0))) ('OUTSIDE', ('TEXT', u'Some ', (None, 1, 6))) (None, ('START', (QName('em'), Attrs()), (None, 1, 11))) (None, ('TEXT', u'test', (None, 1, 15))) (None, ('END', QName('em'), (None, 1, 19))) ('OUTSIDE', ('TEXT', u' text', (None, 1, 24))) ('OUTSIDE', ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :rtype: `Transformer` """ return self.apply(InvertTransformation())
def end(self): """End current selection, allowing all events to be selected. Example: >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer('//em').end().trace()) ('OUTSIDE', ('START', (QName('body'), Attrs()), (None, 1, 0))) ('OUTSIDE', ('TEXT', u'Some ', (None, 1, 6))) ('OUTSIDE', ('START', (QName('em'), Attrs()), (None, 1, 11))) ('OUTSIDE', ('TEXT', u'test', (None, 1, 15))) ('OUTSIDE', ('END', QName('em'), (None, 1, 19))) ('OUTSIDE', ('TEXT', u' text', (None, 1, 24))) ('OUTSIDE', ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :return: the stream augmented by transformation marks :rtype: `Transformer` """ return self.apply(EndTransformation()) #{ Deletion operations
def trace(self, prefix='', fileobj=None): """Print events as they pass through the transform. >>> html = HTML('<body>Some <em>test</em> text</body>', encoding='utf-8') >>> print(html | Transformer('em').trace()) (None, ('START', (QName('body'), Attrs()), (None, 1, 0))) (None, ('TEXT', u'Some ', (None, 1, 6))) ('ENTER', ('START', (QName('em'), Attrs()), (None, 1, 11))) ('INSIDE', ('TEXT', u'test', (None, 1, 15))) ('EXIT', ('END', QName('em'), (None, 1, 19))) (None, ('TEXT', u' text', (None, 1, 24))) (None, ('END', QName('body'), (None, 1, 29))) <body>Some <em>test</em> text</body> :param prefix: a string to prefix each event with in the output :param fileobj: the writable file-like object to write to; defaults to the standard output stream :rtype: `Transformer` """ return self.apply(TraceTransformation(prefix, fileobj=fileobj)) # Internal methods
def __call__(self, stream): """Apply the transform filter to the marked stream. :param stream: The marked event stream to filter """ callable_value = hasattr(self.value, '__call__') for mark, (kind, data, pos) in stream: if mark is ENTER: if callable_value: value = self.value(self.name, (kind, data, pos)) else: value = self.value if value is None: attrs = data[1] - [QName(self.name)] else: attrs = data[1] | [(QName(self.name), value)] data = (data[0], attrs) yield mark, (kind, data, pos)
def is_safe_elem(self, tag, attrs): """Determine whether the given element should be considered safe for inclusion in the output. :param tag: the tag name of the element :type tag: QName :param attrs: the element attributes :type attrs: Attrs :return: whether the element should be considered safe :rtype: bool :since: version 0.6 """ if tag not in self.safe_tags: return False if tag.localname == 'input': input_type = attrs.get('type', '').lower() if input_type == 'password': return False return True
def ET(element): """Convert a given ElementTree element to a markup stream. :param element: an ElementTree element :return: a markup stream """ tag_name = QName(element.tag.lstrip('{')) attrs = Attrs([(QName(attr.lstrip('{')), value) for attr, value in element.items()]) yield START, (tag_name, attrs), (None, -1, -1) if element.text: yield TEXT, element.text, (None, -1, -1) for child in element.getchildren(): for item in ET(child): yield item yield END, tag_name, (None, -1, -1) if element.tail: yield TEXT, element.tail, (None, -1, -1)
def to_genshi(walker): text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
def __call__(self, kind, data, pos, namespaces, variables): qname = QName('%s}%s' % (namespaces.get(self.prefix), self.name)) if kind is START: if self.principal_type is ATTRIBUTE and qname in data[1]: return Attrs([(self.name, data[1].get(self.name))]) else: return data[0] == qname
def test_map_element(self): self.assertEqual( self._map('foo'), [(QName('foo'), Attrs([(QName('name'), u'foo'), (QName('size'), u'100')])), u'FOO', QName('foo')] )
def test_map_with_root_and_end_kind(self): self.assertEqual( self._map('.', END), [QName('foo'), QName('bar'), QName('root')] )
def attr(self, name, value): """Add, replace or delete an attribute on selected elements. If `value` evaulates to `None` the attribute will be deleted from the element: >>> html = HTML('<html><head><title>Some Title</title></head>' ... '<body>Some <em class="before">body</em> <em>text</em>.</body>' ... '</html>', encoding='utf-8') >>> print(html | Transformer('body/em').attr('class', None)) <html><head><title>Some Title</title></head><body>Some <em>body</em> <em>text</em>.</body></html> Otherwise the attribute will be set to `value`: >>> print(html | Transformer('body/em').attr('class', 'emphasis')) <html><head><title>Some Title</title></head><body>Some <em class="emphasis">body</em> <em class="emphasis">text</em>.</body></html> If `value` is a callable it will be called with the attribute name and the `START` event for the matching element. Its return value will then be used to set the attribute: >>> def print_attr(name, event): ... attrs = event[1][1] ... print(attrs) ... return attrs.get(name) >>> print(html | Transformer('body/em').attr('class', print_attr)) Attrs([(QName('class'), u'before')]) Attrs() <html><head><title>Some Title</title></head><body>Some <em class="before">body</em> <em>text</em>.</body></html> :param name: the name of the attribute :param value: the value that should be set for the attribute. :rtype: `Transformer` """ return self.apply(AttrTransformation(name, value)) #{ Buffer operations
def __init__(self, name): """Create the transform. :param name: New element name. """ self.name = QName(name)
def _handle_start(self, tag, attrib): attrs = Attrs([(QName(name), value) for name, value in zip(*[iter(attrib)] * 2)]) self._enqueue(START, (QName(tag), attrs))
def parse(self): """Generator that parses the HTML source, yielding markup events. :return: a markup event stream :raises ParseError: if the HTML text is not well formed """ def _generate(): if self.encoding: reader = codecs.getreader(self.encoding) source = reader(self.source) else: source = self.source try: bufsize = 4 * 1024 # 4K done = False while 1: while not done and len(self._queue) == 0: data = source.read(bufsize) if not data: # end of data self.close() done = True else: if not isinstance(data, unicode): raise UnicodeError("source returned bytes, but no encoding specified") self.feed(data) for kind, data, pos in self._queue: yield kind, data, pos self._queue = [] if done: open_tags = self._open_tags open_tags.reverse() for tag in open_tags: yield END, QName(tag), pos break except html.HTMLParseError, e: msg = '%s: line %d, column %d' % (e.msg, e.lineno, e.offset) raise ParseError(msg, self.filename, e.lineno, e.offset) return Stream(_generate()).filter(_coalesce)
def handle_starttag(self, tag, attrib): fixed_attrib = [] for name, value in attrib: # Fixup minimized attributes if value is None: value = name fixed_attrib.append((QName(name), stripentities(value))) self._enqueue(START, (QName(tag), Attrs(fixed_attrib))) if tag in self._EMPTY_ELEMS: self._enqueue(END, QName(tag)) else: self._open_tags.append(tag)
def handle_endtag(self, tag): if tag not in self._EMPTY_ELEMS: while self._open_tags: open_tag = self._open_tags.pop() self._enqueue(END, QName(open_tag)) if open_tag.lower() == tag.lower(): break