I would like to print the value with the condition: if the IsRecommended.text is true, it will print the value in the same tree only. But the result now is it print all the values included the IsRecommended.text is false.
<Settings>
<Setting>
<Address>15:0</Address>
<Comments />
<Conditions />
<IsSingleEnded>true</IsSingleEnded>
<IsVisibilityExternal>false</IsVisibilityExternal>
<MetaDatas />
<SettingName>123</SettingName>
</Setting>
<Setting>
<Address>18:0</Address>
<Comments />
<Conditions />
<IsSingleEnded>true</IsSingleEnded>
<IsVisibilityExternal>false</IsVisibilityExternal>
<MetaDatas />
<SettingName>abc</SettingName>
</Setting>
<Strings>
<String>
<value>1</value>
<IsRecommended>false</IsRecommended>
</String>
<String>
<value>2</value>
<IsRecommended>true</IsRecommended>
</String>
</Strings>
</Setting>
</Settings>
Here is my code:
from xml.etree import ElementTree
with open('abc.xml', 'rt') as f:
tree = ElementTree.parse(f)
#address1 = tree.findall('.//Address')
#print address1.node.tag
with open("expected.txt", "w") as text_file:
for setting in tree.findall('.//Setting'):
address = setting.find('./Address')
setting_name = setting.find('./SettingName')
strings = setting.find('./Strings')
is_recommended = None
for string in strings.findall('./String'):
for is_recommended in string.findall('./IsRecommended'):
for value in strings.findall('.//value'):
if is_recommended is not None and is_recommended.text == 'true':
print value.text
text_file.write("{} {} {}\n".format(setting_name.text, address.text, value.text))
Any error in my code? How can I solve this problem?
Aucun commentaire:
Enregistrer un commentaire