Python Forum

Full Version: Xpath queries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello

I am able to write some python code, including functions. Thanks for the help

I want to write xPath Queries using Python. I need to analyze large set of xml files.

Can someone please guide me where to start or some samples?

Thanks
Sairam
You can find packages here: https://pypi.python.org/pypi?%3Aaction=s...mit=search
many will come with example code, or you may find some applications which use a particular package here: http://nullege.com/
Thanks
Take a look a this tutorial.
So there use BS and lxml,both work fine for parse xml.
No is it html parsing in tutorial,but not so much difference for xml.

For using xPath is lxml a good choice.
Example:
from lxml import etree

# Simulate xml
xml = '''\
<bookstore>
  <book category="web">
    <title lang="en">XQuery Kick Start</title>
    <author>James McGovern</author>
    <author>Per Bothner</author>
    <author>Kurt Cagle</author>
    <author>James Linn</author>
    <author>Vaidyanathan Nagarajan</author>
    <year>20013</year>
    <price>49.99</price>
    <year>2015</year>
    <price>30</price>
  </book>
</bookstore>
'''

tree = etree.XML(xml)
Test parse with xPath:
>>> x_path = tree.xpath("//title[@lang='en']")
>>> x_path[0].text
'XQuery Kick Start'

>>> x_path = tree.xpath("/bookstore/book[1]/year")
>>> x_path[0].text
'20013'
>>> x_path[1].text
'2015'

>>> x_path = tree.xpath(".//price")
>>> [float(i.text) for i in x_path]
[49.99, 30.0]
I am looking for xml parsing Xpath queries.

Can someone recommend me a simple tutorial for xpath queries to parse xml (no youtube video please)

SaiRam
google 'simple tutorial for xpath queries' you'll be surprised what you'll find
Please refrain from using private mail. The forum is for all to see.
one of the google links was: https://www.codeproject.com/Articles/189...e-to-XPath