0

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 ?

2
  • sorry I should have mentioned that I use xml.dom.minidom , I will give xpath a shot . Commented Jan 15, 2013 at 11:31
  • 2
    @Fingertwist -- if you need to do more of this, do yourself a favour and use lxml Commented Jan 15, 2013 at 11:43

2 Answers 2

4

use xpath:

doc.xpath('.//item[timeleft/text()!="PT0S"]/title/text()')

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.