print tag value from xml using python -


i trying write python script prints value of particular tag in xml output. here, tag value need print value of in each , every occurrences in xml output. tried below, shows attribute error. wrong here? correct way of getting , print values of more tags interested see? please? thanks.

import xml.etree.elementtree et  mystring="""<?xml version="1.0" encoding="utf-8"?> <main>     <student>         <male>             <result>pass</result>             <name>paul</name>             <address>boston</address>             <localreference>                 <name>charlie</name>             </localreference>         </male>         <female>             <result>pass</result>             <name>rose</name>             <address>newyork</address>             <localreference>                 <name>charlie</name>             </localreference>         </female>     </student>     <student>         <male>             <result>fail</result>             <name>philippe</name>             <address>boston</address>             <localreference>                 <name>white</name>             </localreference>         </male>     </student> </main>"""  main = et.fromstring(mystring) student in main:   if (student.tag == "student"):       print student.find("male/result").text       print student.find("female/result").text 

error>

# python new5.py pass pass fail traceback (most recent call last):   file "new5.py", line 39, in <module>     print student.find("female/result").text attributeerror: 'nonetype' object has no attribute 'text' 

elementtree supports subset of xpath, , may easier example:

root = et.fromstring(mystring) gender in ('male', 'female'):     print gender     student in root.findall('./student/%s' % gender):          print '\t{:20}: {}'.format(student.find('name').text, student.find('result').text) 

prints:

male     paul                : pass     philippe            : fail female     rose                : pass 

(btw: avoid using main variable name since clobber name of main module)


if want results in document order rather grouped gender, might like:

for students in root.findall('./student'):     gender in students:         print ' '.join([gender.tag] + map(lambda a: gender.find(a).text, ('name', 'address', 'result', 'localreference/name'))) 

prints

male paul boston pass charlie female rose newyork pass charlie male philippe boston fail white 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -