Marco Dinatsoli
Marco Dinatsoli

Reputation: 10570

python how to get tag from xml in python

I have an xml

and I check if it is existed like this:

s = os.path.isfile(xmlFile)

I am loading it like this:

from lxml import etree
self.doc=etree.parse(xmlFile)

my questoin

how to get tags from that doc? lets say i have tag called "domain" and tag called "player" existed in "root/team/hello/player"

Upvotes: 1

Views: 242

Answers (1)

Sudeep Juvekar
Sudeep Juvekar

Reputation: 5068

The lxml documentation says that parse() method returns an ElementTree object in lxml and then you can call getroot() on that to get the root Element. Isn't that the missing piece you were looking for? Will something like this work?

self.doc=etree.parse(xmlFile)
root = self.doc.getroot() # Element object root

I guess once you get the Element, you can call subElement/child etc. methods given in the tutorial.

child_team = etree.subElement(root, "team")
child_hello = etree.subElement(child_team, "hello")
child_player = etree.subElement(child_hello, "player")

Check out this link for details: http://lxml.de/tutorial.html#the-parse-function

Upvotes: 1

Related Questions