0

I can not find the appropriate syntax or method to do this, which is why I am reaching out.

I am using python 2.7 lxml etree

my code is similar to this:

for y in mytree.iterfind('./level1/level2/level3/[2]'):
  print y.tag, y.text

Essentially printing all of the available tags and text in the second iteration of the level. (I know how many there are, I am not having issues with indexing or making the function work).

I am attempting to loop through them using 'i' as a defined variable (incrementally increasing 'i' to the defined number of items).

This does not work:

for y in mytree.iterfind('./level1/level2/level3/[i]'):
  print y.tag, y.text

I also tried creating the string as a variable (concatenating the text with the 'i variable as a string, but python did not recognize that it was a function anymore.

Any suggestions or help would be appreciated.

1 Answer 1

1

You need to build the path string using the value of i, e.g (untested):

for y in mytree.iterfind('./level1/level2/level3/[%d]'%(i)):
  print y.tag, y.text

If in doubt, construct the string outside the interfind call so you can print it, e.g. (untested):

for i in range(3): # or whatever the i loop is...
    pathstr = './level1/level2/level3/[%d]'%(i)
    print pathstr
    for y in mytree.iterfind(pathstr):
        print y.tag, y.text
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, that worked perfectly. I have to learn how that works, meaning the syntax with the %d and %I. I have experience working with macros so searching for this will work now that you pointed me in the right direction by giving me the answer. I am still very new to python. I appreciate the help!
Do note: str.format is preferred to the modulo operator which the latter is used here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.