libxml2 and XPath - Iterate through repeating elements?

Paul Boddie paul at boddie.org.uk
Fri Dec 2 13:41:56 EST 2005


nickhepples... at gmail.com wrote:
> I'm trying to iterate through repeating elements to extract data using
> libxml2 but I'm having zero luck - any help would be appreciated.

Here's how I attempt to solve the problem using libxml2dom [1] (and I
imagine others will suggest their own favourite modules, too):

import libxml2dom
d = libxml2dom.parseFile(filename)
order_numbers = d.xpath("//so:order/so:header/so:orderno",
namespaces={"so" : "some-ns"})

At this point, you have a list of nodes. (I imagine that whatever
object the libxml2 module API produces probably has those previous and
next attributes to navigate the result list instead.) The nodes in the
list represent the orderno elements in this case, and in libxml2dom you
can choose to invoke the usual DOM methods on such node objects, or
even the toString method if you want the document text. For the line
items...

lines = d.xpath("//so:order/so:lines/so:line", namespaces={"so" :
"some-ns"})
for line in lines:
    print line.toString()

I can't remember what the libxml2 module produces for the content
attribute of a node, although the underlying libxml2 API produces a
"text-only" representation of the document text, as opposed to the
actual document text that the toString method produces in the above
example. I imagine that an application working with the line item
information would use additional DOM or XPath processing to get the
line item index and the product code directly.

Anyway, I recommend libxml2dom because if you're already using the
bundled libxml2 module, you should be able to install libxml2dom and
plug into the same infrastructure that the bundled module depends upon.
Moreover, libxml2dom is a "pure Python" package that doesn't require
any extension module compilation, so it should be quite portable to
whatever platform you're using.

Paul

[1] http://www.python.org/pypi/libxml2dom




More information about the Python-list mailing list