[注意我对 Python 和 Xpath 很陌生]
我想执行一个 Xpath 查询并在表达式中使用一个变量来使用索引循环遍历所有元素。
例如,我希望能够放置一个变量 ,而不是
在这个表达式中:[1]
、[2]
等特定位置>i
for x in root.xpath('/movies/a_movie[i]/studio'):
print "<studio>" + x.text + "</studio>"
我不确定这是否可能,但我想问问也无妨!
澄清一下,这就是我想要这样做的原因:我正在尝试处理 a_movie[1]
的所有元素,然后在函数结束时,我想处理a_movie[2]
的所有元素,依此类推。
最佳答案
你想循环遍历 /movies/a_movie
标签,但只有那些有 studio
子标签:
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>"
如果您只想将 a_movie
元素的子元素打印为 XML,我只需遍历该元素(遍历子元素)并使用 ElementTree.tostring ()
在每个:
for a_movie in root.xpath('/movies/a_movie'):
for elem in a_movie:
print ElementTree.tostring(elem),
关于python - 在 Python 中使用变量进行 Xpath 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15680308/