0

I am new to python xml parsing. I am parsing an xml file using elementtree concept.

I went through the domumentation and i have written a script in python.

doc = parse(filePath)

name = doc.getElementsByTagName('package')

print(name)
child_name = name[0]
print(child_name)
print(child_name.tag)
print(child_name.attrib)

The code works to an extent, but the output of child_name.tag and child_name.attrib does not work. When i execute i get his error:

AttributeError: 'Element' object has no attribute 'tag'

In the xml file for the elements the package has id, name, alias , comments desc and so on. I need to access these stuffs.

Can anyone please tell me how i should approach this problem

sankar
  • 347
  • 3
  • 4
  • 15

1 Answers1

0

Both of these

print(child_name.tag)
print(child_name.attrib)

Will give an error.

To approach this use:

print(child_name['tag'])
print(child_name['attrib'])

However, when doing this method you need absolute assurance that the structure does not change.

One way is to use

try:
   print(child_name['tag'])
   print(child_name['attrib'])
catch:
   pass

Where pass is you should consider different indexes.

For this part you could:

for item in name:
   print(item)
Alex Stewart
  • 730
  • 3
  • 12
  • 30
  • Hi i tried to use the way that you have suggested. But still i am not able to go along with it. I did not get any output again, though i am still able to get some output like: ``. But how to access these elements, is still something that i am trying to find out. – sankar Jul 01 '14 at 09:30
  • Try using this `the_page = xmltodict.parse(doc)` make sure to `import xmltodict`. Then you should be able to perform a dictionary access on the file. Otherwise try this: http://stackoverflow.com/questions/18834393/python-xml-file-open – Alex Stewart Jul 01 '14 at 10:23
  • I solved the problem, it was a simple one, i used `root.iter('package')` and i got the output i needed. – sankar Jul 01 '14 at 12:44