2013-01-15 112 views
0

我有這個XML文件:解析XML的childNodes

<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> 

我想返回「標題」如果「的timeleft」不是「PT0S」:

到目前爲止,我得到這個:

itemList = response.getElementsByTagName('Item') 
children = itemList[0].childNodes 
for child in children : 
    if child.tagName == "TimeLeft": 
    if child.childNodes[0].nodeValue == "PT0S": 
     print "ping" 

但我不知道該怎麼要回從那裏「標題」值,這將是返回一個childnode的價值取決於如果其他childnode是真的還是假的更優雅的方式?

+0

有沒有試過xpath? – farmer1992

+0

對不起,我應該提到我使用xml.dom.minidom,我會給xpath一個鏡頭。 –

+2

@Fingertwist - 如果你需要做更多的事情,請幫個忙,並使用lxml – root

回答

4

使用xpath

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

2

您可以使用Python的ElementTree API和簡單的列表理解:

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將是項目的標題的列表,這TimeLeftPT0S 。在我看來,這比基於XPath的解決方案(如果您不熟悉XPath)更容易閱讀。