Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read root XML tag in python

My question follows on from another stackoverflow question:- "How to get the root node of an xml file in Python?"

from xml.etree import ElementTree as ET
path = 'C:\cool.xml'
et = ET.parse ( path )
root = et.getroot()

When I extract and print the root tag, I receive:-

<Element 'root' at 0x1234abcd>

I then want to check that the root tag has a certain title, how do I pull out just the tag name?

If I try:

if root == "root":
    print 'something'

it doesn't work, so I assume I need to convert 'root' to text or something like that? I am very new to Python.

like image 396
user788462 Avatar asked Sep 19 '11 00:09

user788462


2 Answers

You should be able to use the tag function to get the name of the node.

from xml.etree import ElementTree as ET
path = 'C:\cool.xml'
et = ET.parse ( path )
root = et.getroot()

if root.tag == "root":
  print "I'm the root"
like image 169
Michael Anderson Avatar answered Oct 14 '22 07:10

Michael Anderson


root is an instance of the Element class. Any such object will have a tag attribute. Just use root.tag. Given what you say in your question, this should produce the string "root".

like image 3
John Machin Avatar answered Oct 14 '22 05:10

John Machin