我试图从看起来像这样的xml数据中获取名称:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Major Version</key><integer>1</integer>
<key>Minor Version</key><integer>1</integer>
<dict>
<key>369</key>
<dict>
<key>Track ID</key><integer>369</integer>
<key>Name</key><string>Another One Bites The Dust</string>
<key>Artist</key><string>Queen</string>
</dict>
<key>371</key>
<dict>
<key>Track ID</key><integer>371</integer>
<key>Name</key><string>Asche Zu Asche</string>
<key>Artist</key><string>Rammstein</string>
</dict>
我正在尝试以下代码,该代码为我提供了<key>
tag的文本值。考虑到第一个标签的文本值为Name,我需要第二个标签的文本值。因此,所需的输出是“另一个咬住灰尘”和“ Asche Zu Zuche”
import xml.etree.ElementTree as ET
stuff = ET.parse(fname)
all = stuff.findall('dict/dict/dict')
for item in all:
for child in item :
if child.tag == 'key' and child.text == 'Name':
print(child.text)
要使用ET进行操作,请尝试以下操作:
all = stuff.findall('dict/dict')
for item in all:
children = item.findall('.//key')
for child in children:
if child.text=="Name":
print(item.find('.//string').text)
最简单的方法是使用lxml而不是xml.etree,因为lxml具有更好的xpath支持。这样,它非常简单:
from lxml import etree
stuff = ET.parse(fname)
all = stuff.xpath('//dict/dict/key[.="Name"]/following-sibling::*[1]')
for a in all:
print(a.text)
在这两种情况下,输出均为:
Another One Bites The Dust
Asche Zu Asche
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句