I have got this xml file :
<ItemArray>
<Item>
<GiftIcon>0</GiftIcon>
<HitCounter>NoHitCounter</HitCounter>
<Quantity>1</Quantity>
<TimeLeft>P9DT17H35M6S</TimeLeft>
<Title>Table</Title>
</Item>
<Item>
<GiftIcon>0</GiftIcon>
<HitCounter>NoHitCounter</HitCounter>
<Quantity>1</Quantity>
<TimeLeft>PT0S</TimeLeft>
<Title>Chair</Title>
</Item>
</ItemArray>
I would like to return "Title" if "TimeLeft" is not "PT0S" :
So far I have got this :
itemList = response.getElementsByTagName('Item')
children = itemList[0].childNodes
for child in children :
if child.tagName == "TimeLeft":
if child.childNodes[0].nodeValue == "PT0S":
print "ping"
But I don't know how to get back to the "Title" value from there, what would be a more elegant way to return a childnode's value depending if an other childnode is true or false ?
use xpath
:
doc.xpath('.//item[timeleft/text()!="PT0S"]/title/text()'
)
You can use Python's ElementTree API and simple list comprehension:
import xml.etree.ElementTree as ET
tree = ET.parse('your_xml_file.xml')
root = tree.getroot()
titles = [item.find('Title').text for item in root.findall('Item') if item.find('TimeLeft').text != 'PT0S']
titles
will be a list of titles of items for which TimeLeft
is not PT0S
. This is easier to read than an XPath-based solution (if you're not familiar with XPath) in my opinion.
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.