Transforming XIST trees

The mapped function, sorting, etc.

Home › Python software › ll.xist › TransformationText · XIST

Apart from the convert method, XIST provides many tools for manipulating an XML tree.

The withsep method

The method withsep can be used to put a seperator node between the child nodes of an Element or a Frag:

>>> from ll.xist import xsc
>>> from ll.xist.ns import html
>>> node = html.div(xrange(10))
>>> print node.withsep(", ").bytes()
<div>0, 1, 2, 3, 4, 5, 6, 7, 8, 9</div>

The shuffled method

The method shuffled returns a shuffled version of the Element or Frag:

>>> from ll.xist import xsc
>>> from ll.xist.ns import html
>>> node = html.div(xrange(10))
>>> print node.shuffled().withsep(", ").bytes()
<div>8, 1, 3, 6, 7, 5, 2, 9, 4, 0</div>

The reversed and sorted methods

There are methods named reversed and sorted that return a reversed or sorted version of an element or fragment:

>>> from ll.xist import xsc
>>> from ll.xist.ns import html
>>> def key(n):
... 	return unicode(n)
>>> node = html.div(8,4,2,1,9,6,3,0,7,5)
>>> print node.sorted(key=key).reversed().withsep(",").bytes()
<div>9,8,7,6,5,4,3,2,1,0</div>

The mapped method

The method mapped recursively walks the tree and generates a new tree, where all the nodes are mapped through a function. An example: To replace Python with Parrot in every text node on the Python page, do the following:

from ll.xist import xsc, parse

def p2p(node, converter):
·  if isinstance(node, xsc.Text):
·  ·  node = node.replace(u"Python", u"Parrot")
·  ·  node = node.replace(u"python", u"parrot")
·  return node

node = parse.tree(parse.URL("http://www.python.org"), parse.Tidy(), parse.NS(html), parse.Node(pool=xsc.Pool(xml, html)))
node = node.mapped(p2p)
node.write(open("parrot_index.html", "wb"))

The function must either return a new node, in which case this new node will be used instead of the old one, or return the old node to tell mapped that it should recursively continue with the content of the node.