简体   繁体   中英

while parsing xml getting none type even it has some value,how can i solve this issue?

input
As you can see guys the xml code that i am trying to parse,has value in name then how can it be NoneType?

import xml.etree.ElementTree as ET
input='''
  <stuff>
    <user>
      <user x='2' >
        <id>001</id>
        <name>chuck</name>
     </user>
     <user x ='7'>
       <id>009</id>
       <name>brent</name>
       </user>
     </user>
    </stuff>

     '''
stuff=ET.fromstring(input)
print(stuff.find('name').text)

output

AttributeError             Traceback (most recent call last)
<ipython-input-7-f10e349a116e> in <module>
     16      '''
     17 stuff=ET.fromstring(input)
---> 18 print(stuff.find('name').text)

AttributeError: 'NoneType' object has no attribute 'text'

You need to specify the correct xpath syntax to get to the sub-child name tag.

Try this:

print(stuff.find('.//name').text)

Result:

chuck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM