libxml2 and XPath - Iterate through repeating elements?
Jean-Roch SOTTY
jrsotty at cri74.org
Mon Dec 5 05:31:24 EST 2005
Le Vendredi 2 Décembre 2005 18:31, nickheppleston at gmail.com a écrit :
> I'm trying to iterate through repeating elements to extract data using
> libxml2 but I'm having zero luck - any help would be appreciated.
>
> My XML source is similar to the following - I'm trying to extract the
> line number and product code from the repeating line elements:
>
> <order xmlns="some-ns">
> <header>
> <orderno>123456</orderno>
> </header>
> <lines>
> <line>
> <lineno>1</lineno>
> <productcode>PENS</productcode>
> </line>
> <line>
> <lineno>2</lineno>
> <productcode>STAPLER</productcode>
> </line>
> <line>
> <lineno>3</lineno>
> <productcode>RULER</productcode>
> </line>
> </lines>
> </order>
The result of an xpath evaluation is a list of node, which you can perform
another xpatheval() on :
import libxml2
doc = libxml2.parseFile(XmlFile)
root = doc.getRootElement()
line_nodes = root.xpathEval('lines/line')
for line_node in line_nodes:
print line_node.xpathEval('lineno')[0].content
print line_node.xpathEval('productcode')[0].content
doc.freeDoc()
--
Cordially
Jean-Roch SOTTY
More information about the Python-list
mailing list