在python中解析xml子节点
我得到了这个xml文件:在python中解析xml子节点,python,xml,Python,Xml,我得到了这个xml文件: <ItemArray> <Item> <GiftIcon>0</GiftIcon> <HitCounter>NoHitCounter</HitCounter> <Quantity>1</Quantity> <TimeLeft>P9DT17H35M6S</TimeLeft> <T
<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>
但是我不知道如何从那里返回到“Title”值,根据另一个childnode的值是真是假,有什么更优雅的方法返回childnode的值呢?使用
xpath
:
doc.xpath('.//item[timeleft/text()!=“PT0S”]/title/text()
)使用xpath
:
doc.xpath('.//item[timeleft/text()!=“PT0S”]/title/text()'
)您可以使用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
将是TimeLeft
不是PT0S
的项目的标题列表。在我看来,这比基于XPath的解决方案(如果您不熟悉XPath)更容易阅读。您可以使用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
将是TimeLeft
不是PT0S
的项目的标题列表。在我看来,这比基于XPath的解决方案(如果您不熟悉XPath)更容易阅读。对不起,我应该提到我使用了xml.dom.minidom,我会给XPath一个机会。@Fingertwist--如果您需要做更多的工作,请帮自己一个忙,使用LXML。对不起,我应该提到我使用了xml.dom.minidom,我将给xpath一个机会。@Fingertwist——如果您需要做更多的工作,请帮自己一个忙并使用lxml