Reputation: 2364
I have the following XML which I have parsed from a webpage:
<!--
Parts from the iGEM Registry of Standard Biological Parts
-->
<rsbpml>
<part_list>
<part>
<part_id>151</part_id>
<part_name>BBa_B0034</part_name>
<part_short_name>B0034</part_short_name>
<part_short_desc>RBS (Elowitz 1999) -- defines RBS efficiency</part_short_desc>
<part_type>RBS</part_type>
<release_status>Released HQ 2013</release_status>
<sample_status>In stock</sample_status>
<part_results>Works</part_results>
<part_nickname>SAMT</part_nickname>
<part_rating/>
<part_url>http://parts.igem.org/Part:BBa_J45001</part_url>
<part_entered>2006-06-07</part_entered>
<part_author>Kate Broadbent</part_author>
<deep_subparts/>
<specified_subparts/>
<specified_subscars/>
<sequences>...</sequences>
<features>...</features>
<parameters>
<!--...-->
<!--...-->
<parameter>...</parameter>
<parameter>
<name>swisspro</name>
<value>Q8H6N2</value>
I have some code to return the swisspro
parameter value; Q8H6N2
. However, I want the code to throw up an error if there is no swisspro
parameter present.
So far I have tried the code below but it does not work:
def part_attrib(self,x):
if x == 'uniprot_id':
for parameter in self.root.iter(tag='parameter'):
name = parameter.find('name')
if name is not None and name.text == 'swisspro':
return parameter.find('value').text
else:
return "No UniProt ID present."
With that else
statement present, the code always outputs the error statement whether or not there is a swisspro
parameter present. If I omit the else
argument, the code works but does not throw up an error if there is no swisspro
parameter present.
What am I doing wrong?
I should highlight that there are several of these <paramter>
sections in the XML.
Upvotes: 0
Views: 726
Reputation: 86
Since you're returning in your for loop, you could also just return your error message if you make it to the end of the function,
def part_attrib(self,x):
if x == 'uniprot_id':
for parameter in self.root.iter(tag='parameter'):
name = parameter.find('name')
if name is not None and name.text == 'swisspro':
return parameter.find('value').text
return "No UniProt ID present."
Upvotes: 0
Reputation: 2482
You can set a value before the loop:
swisspro_value = None
for parameter in self.root.iter(tag='parameter'):
name = parameter.find('name')
if name is not None and name.text == 'swisspro':
swisspro_value = parameter.find('value').text
break
return swisspro_value or "No UniProt ID present."
Upvotes: 1