| 1 | from genshi.core import Attrs, Stream, QName |
|---|
| 2 | |
|---|
| 3 | class ElementTreeStream(Stream): |
|---|
| 4 | """ |
|---|
| 5 | Adapted from function ET in genshi.template from Genshi 0.3.4. |
|---|
| 6 | |
|---|
| 7 | This allows you to select(...) the resulting stream. It also unwraps lists |
|---|
| 8 | passed in, specifically to handle the result of element.findall(...). |
|---|
| 9 | """ |
|---|
| 10 | |
|---|
| 11 | @classmethod |
|---|
| 12 | def convert(cls, element): |
|---|
| 13 | tag_name = element.tag |
|---|
| 14 | if tag_name.startswith('{'): |
|---|
| 15 | tag_name = tag_name[1:] |
|---|
| 16 | tag_name = QName(tag_name) |
|---|
| 17 | attrib = Attrs(element.items()) |
|---|
| 18 | |
|---|
| 19 | yield (Stream.START, (tag_name, attrib), (None, -1, -1)) |
|---|
| 20 | if element.text: |
|---|
| 21 | yield Stream.TEXT, element.text, (None, -1, -1) |
|---|
| 22 | for child in element.getchildren(): |
|---|
| 23 | for item in cls.convert(child): |
|---|
| 24 | yield item |
|---|
| 25 | yield Stream.END, tag_name, (None, -1, -1) |
|---|
| 26 | if element.tail: |
|---|
| 27 | yield Stream.TEXT, element.tail, (None, -1, -1) |
|---|
| 28 | # |
|---|
| 29 | |
|---|
| 30 | def __iter__(self): |
|---|
| 31 | if isinstance(self.events, list): |
|---|
| 32 | from itertools import chain |
|---|
| 33 | return chain(*(self.convert(element) for element in self.events)) |
|---|
| 34 | |
|---|
| 35 | else: |
|---|
| 36 | return self.convert(self.events) |
|---|
| 37 | # |
|---|
| 38 | # |
|---|
| 39 | |
|---|
| 40 | |
|---|
| 41 | |
|---|
| 42 | # End |
|---|