1
0

genshi.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from __future__ import absolute_import, division, unicode_literals
  2. from genshi.core import QName, Attrs
  3. from genshi.core import START, END, TEXT, COMMENT, DOCTYPE
  4. def to_genshi(walker):
  5. """Convert a tree to a genshi tree
  6. :arg walker: the treewalker to use to walk the tree to convert it
  7. :returns: generator of genshi nodes
  8. """
  9. text = []
  10. for token in walker:
  11. type = token["type"]
  12. if type in ("Characters", "SpaceCharacters"):
  13. text.append(token["data"])
  14. elif text:
  15. yield TEXT, "".join(text), (None, -1, -1)
  16. text = []
  17. if type in ("StartTag", "EmptyTag"):
  18. if token["namespace"]:
  19. name = "{%s}%s" % (token["namespace"], token["name"])
  20. else:
  21. name = token["name"]
  22. attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value)
  23. for attr, value in token["data"].items()])
  24. yield (START, (QName(name), attrs), (None, -1, -1))
  25. if type == "EmptyTag":
  26. type = "EndTag"
  27. if type == "EndTag":
  28. if token["namespace"]:
  29. name = "{%s}%s" % (token["namespace"], token["name"])
  30. else:
  31. name = token["name"]
  32. yield END, QName(name), (None, -1, -1)
  33. elif type == "Comment":
  34. yield COMMENT, token["data"], (None, -1, -1)
  35. elif type == "Doctype":
  36. yield DOCTYPE, (token["name"], token["publicId"],
  37. token["systemId"]), (None, -1, -1)
  38. else:
  39. pass # FIXME: What to do?
  40. if text:
  41. yield TEXT, "".join(text), (None, -1, -1)