简体   繁体   中英

Use a variable for an Xpath query in Python

[NB I'm quite new to Python & Xpath]

I was wanting to perform an Xpath query and use a variable in the expression to cycle through all the elements using an index.

For example, rather than having the specific position of [1] , [2] , etc, I'd like to be able to place a variable i in this expression:

for x in root.xpath('/movies/a_movie[i]/studio'):
    print "<studio>" + x.text + "</studio>"

I'm unsure whether it's even possible, but I guess it can't hurt to ask!

To clarify, this is why I would like to do this: I'm trying to process all the elements of a_movie[1] , then at the end of the function, I want to process all the elements of a_movie[2] , and so on.

You want to loop over the /movies/a_movie tags instead, but only those that have a studio child:

for a_movie in root.xpath('/movies/a_movie[studio]'):
    name = a_movie.find('name').text
    studio = a_movie.find('studio')
    print "<studio>" + studio.text + "</studio>"

If you wanted to just print out the child elements of the a_movie element as XML, I'd just loop over the element (looping over the child elements) and use ElementTree.tostring() on each:

for a_movie in root.xpath('/movies/a_movie'):
    for elem in a_movie:
        print ElementTree.tostring(elem),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM