December 02, 2009

Python XML Processing - libxml2

« Maven Site Example | Main | HTML convert to Pdf in Java »
Libxml is a Python wrapper around the libxml2 library. Other APIs are PyXML and 4Suite. The libxml2 wrapper API enables the developer to use XPath expressions for iteration of XML files. The following example describes the usage.

Sample XML file:
<?xml version="1.0"?>
<orders>
  <order id="1" name="Red T-Shirt" customerId="2" count="2"/>
  <order id="2" name="Blue T-Shirt" customerId="2" count="1"/>
</orders>
XML processing code:
import libxml2

def listAllOrders(xmlFile):
  doc = libxml2.parseFile(xmlFile)
  for order in doc.xpathEval('//order'):
    rowResult = "OrderId is " + order.xpathEval('@id')[0].content
    print rowResult
  doc.freeDoc()

listAllOrders('sample.xml')
Output:
OrderId is 1
OrderId is 2
Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 8:59 AM in Uncategorized

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« December »
SunMonTueWedThuFriSat
  12345
6789101112
13141516171819
20212223242526
2728293031