Apart from the convert
method, XIST provides several tools for manipulating an XML tree.
The withsep
method
The shuffled
method
The reversed
method
The method reversed
returns a reversed version of an element or fragment:
>>>
from ll.xist import xsc
>>>
from ll.xist.ns import html
>>>
node = html.div(range(10))
>>>
print(node.reversed().withsep(",").string())
<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("Python", "Parrot") · · node = node.replace("python", "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.