11.8. Manipulating Trees

The DOM is a read/write API. In addition to reading the values in the document tree's nodes, it provides methods to rearrange and delete nodes. Consider the following XML document, which contains price information for some commodity.

CD-ROM reference=11008.txt
<?xml version="1.0"?>
<prices>
<price>12</price><price>10</price>
<price>54</price><price>9</price>
</prices>

The program below uses the DOM to reorder the price elements in ascending numerical order. It takes advantage of the fact that Python's built-in sort method for list objects allows a custom sort function to be used.

 CD-ROM reference=11009.txt """ Example of rearranging a DOM tree Sorts prices into descending order """ # Import core DOM. from xml.dom import ...

Get XML Processing with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.