Quickest/Best way to traverse XML with lxml in Python?

You can use XPath: for x in target. Xpath('/root/targetroot/targetcontainer/target'): print x. Text We ask all elements that match a path.In this case, the path is /root/targetroot/targetcontainer/target, which means all the elements that are inside a element, inside a element, inside a element.

Also, the element should be the document root because it is preceded by /, which means the beginning of the document. Also, your XML document had two problems. First, the declaration should be the very first thing in the document - and in this example it is preceded by a newline and some space.

Also, it is not a tag and should not be closed, so the at the end of your string should be removed. I already edited your question anyway. EDIT: this solution can be improved yet.

You do not need to pass all the path - you can just ask to all elements inside the document. This is done by preceding the tag name by two slashes. Since you want all the texts, independent of where they are, this can be a better solution.

So, the loop above can be written just as: for x in target. Xpath('//target'): print x. Text I tried it at first but it did not worked.

The problem, however, was the syntax problems in the XML, not the XPath, but I tried the other, longer path and forgot to retry this one. Sorry! Anyway, I hope I put some light about XPath nonetheless :).

The tags are my error, the actual xml has the right syntax. The xpath thing works great, thanks! Cleaner code = cleaner.

– Roland 2 hours ago @Roland actually, it can be made still cleaner. I edited the answer, take a look! – brandizzi 2 hours ago.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions