form filling XML

Paul Boddie paul at boddie.org.uk
Thu Oct 13 14:10:31 EDT 2005


George wrote:
>

[form]

> <li>Monday</li>
> <li>Tuesday</li>
> <li>Wednesday</li>
> <li>Thursday</li>
> <li>Friday</li>

[fillin]

> <dutchdays>
> <Monday>maandag</Monday>
> <Tuesday>dinsdag</Tuesday>
> <Wednesday>woensdag</Wednesday>

[...]

> How can I compare the text in the element tags <li> with the elements
> tags in filling and if they match replace the text within the elements
> tags <li> with the text in the matching element tag of fillin.

You need to first get each of the li elements in form - something which
is best done using XPath:

from xml.dom.minidom import parseString
import xml.xpath
form_doc = parseString(form)
for li in xml.xpath.Evaluate("//li", form_doc):
    Do something with the element.

Here, the XPath expression "//li" means "get all li elements in the
document". When you're examining an li element, you need to get the
textual content in order to find out which day it is you want to
replace. I recommend the following:

li.normalize()
day_text = li.childNodes[0]
day_str = day_text.nodeValue

With this, you have the string value of the day (rather than some
node), and can then go looking for that day's Dutch translation in the
other document using similar techniques. Since you look for the
translation for each li element, you're going to be using nested loops
rather than a single one.

I hope this gets you started on the problem, anyway!

Paul




More information about the Python-list mailing list