0

First : am a new beg. using python..so please help me out.I'm trying to read a XML file using Python. My xml file name is rgpost.xml

<volume name="sp" type="span" operation="create">
    <driver>HDD1</driver>
</volume>

My code :

import xml.etree.ElementTree as ET
doc = ET.parse("rgpost.xml")
s = doc.find("volume")
print s.attrib["name"]

While running this am getting error :

sp:~# python volume_check.py volume  
Traceback (most recent call last):  
  File "volume_check.py", line 13, in <module>  
    print s.attrib["name"]  
AttributeError: 'NoneType' object has no attribute 'attrib'

Thanks in advance

3
  • 1
    Never run your script as root unless you really have to. Commented Oct 21, 2012 at 12:31
  • i change root.but still not workingg Commented Oct 21, 2012 at 12:35
  • 1
    This was rather a recommendation than a fix for your problem. It's a good practice, imagine your script has a severe bug that causes data loss and has root access... Commented Oct 21, 2012 at 12:40

2 Answers 2

3

Life is much easier if you get the root:

>>> import xml.etree.ElementTree as ET
>>> doc = ET.parse("rgpost.xml")
>>> root = doc.getroot() # <--- this is the new line
>>> root
<Element 'volume' at 0x1004d8f10>
>>> root.keys()
['operation', 'type', 'name']
>>> root.attrib["name"]
'sp'
>>> root.get("name")
'sp'
Sign up to request clarification or add additional context in comments.

1 Comment

Great baba great...super :) its working. Thanks for your time
1

volume is considered the root of the XML tree, so what you want is effectively doc.attrib['name'].

xml="""<volume name="sp" type="span" operation="create">
    <driver>HDD1</driver>
</volume>"""

import xml.etree.ElementTree as ET
doc = ET.fromstring(xml)
print doc
# <Element 'volume' at 0x26f1d50>
print doc.attrib['name']

1 Comment

not working still :( AttributeError: ElementTree instance has no attribute 'attrib'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.