How *build* new elements and *replace* elements with xml.dom.minidom ?

Stefan Behnel stefan_ml at behnel.de
Thu Jun 11 02:22:14 EDT 2009


Chris Seberino wrote:
> How build new elements to replace existing ones using xml.dom.minidom?
> 
> Specifically, I have an HTML table of numbers.  I want to replace
> those numbers with hyperlinks to create a table of hyperlinks.
> 
> So I need to build hyperlinks (a elements) with href attribute and
> replace the text elements (numbers) somehow.

Try lxml.html instead. It makes it really easy to do these things. For
example, you can use XPath to find all table cells that contain numbers:

	td_list = doc.xpath("//td[number() >= 0]")

or maybe using regular expressions to make sure it's an int:

	td_list = doc.xpath("//td[re:match(., '^[0-9]+$')]",
              namespaces={'re':'http://exslt.org/regular-expressions'})

and then replace them by a hyperlink:

	# assuming links = ['http://...', ...]

	from lxml.html.builder import A
	for td in td_list:
		index = int(td.text)
		a = A("some text", href=links[index])
		td.getparent().replace(td, a)

Stefan



More information about the Python-list mailing list