libxml2 and XPath - Iterate through repeating elements?

nickheppleston at gmail.com nickheppleston at gmail.com
Fri Dec 2 12:31:20 EST 2005


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>

With the following code I can get at the non-repeating elements in the
header, and get the lines elements, but cannot extract the
lineno/productcode data via xpath:

	XmlDoc = libxml2.parseFile(XmlFile);
	XPathDoc = XmlDoc.xpathNewContext();
	XPathDoc.xpathRegisterNs('so',"some-ns");


	# Extract data from the order header
	PurchaseOrderNo =
XPathDoc.xpathEval('//so:order/so:header/so:orderno');

	# Extract data from the order lines
	for line in XPathDoc.xpathEval('//so:order/so:lines/so:line'):
		print line.content;

	# Explicitly free Xml document and XPath context
	XmlDoc.freeDoc()
	XPathDoc.xpathFreeContext()

Ideally, I'd like to select the line data using xpath (similar to an
XSLT query after a 'for-each' - i.e. xpathEval('so:lineno') and
xpathEval('so:productcode') once I've got the line element).

Any suggestions grealty appreciated!

Cheers, Nick.




More information about the Python-list mailing list