0

私はこのxmlファイルを持っています:

 <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" でない場合は "Title" を返したい:

これまでのところ、私はこれを持っています:

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

しかし、そこから「タイトル」値に戻る方法がわかりません。他の子ノードが true または false であるかどうかに応じて、子ノードの値を返すよりエレガントな方法は何でしょうか?

4

2 に答える 2

4

使用xpath

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

于 2013-01-15T11:23:58.847 に答える
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']

titlesTimeLeftではないアイテムのタイトルのリストになりますPT0S。私の意見では、これは XPath ベースのソリューション (XPath に慣れていない場合) よりも読みやすいものです。

于 2013-01-15T14:22:30.350 に答える