Python 3.x 使用xml.etree从xml获取特定标记的Fecth数据
我试图从一个xml数据中获取名称,该数据看起来有点像:Python 3.x 使用xml.etree从xml获取特定标记的Fecth数据,python-3.x,xml,xml.etree,Python 3.x,Xml,Xml.etree,我试图从一个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>
<?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>
要使用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
要使用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