3 回答

TA貢獻1852條經驗 獲得超7個贊
正如@AmitaiIrron 所建議的,xpath可以在這里提供幫助。
此代碼在文檔中搜索名為 的元素zip-code,然后返回 ping 以獲取該元素的父元素。從那里,您可以獲得屬性,并與元素name中的文本配對zip-code
for ent in root.findall(".//zip-code/.."):
print(ent.attrib.get('name'), ent.find('zip-code').text)
studio 14407
mailbox 33896
garage 33746
gym 33746
要么
{ent.attrib.get('name') : ent.find('zip-code').text
for ent in root.findall(".//zip-code/..")}
{'studio': '14407', 'mailbox': '33896', 'garage': '33746', 'gym': '33746'}

TA貢獻1804條經驗 獲得超7個贊
你的循環應該是這樣的:
# Find all <entry> tags in the hierarchy
for item in root.findall('.//entry'):
# Try finding a <zip-code> child
zipc = item.find('./zip-code')
# If found a child, print data for it
if zipc is not None:
names = (item.attrib)
print(' {} {} '.format(
names, zipc.text
))
在搜索 XML 樹時,學習正確使用xpath是個問題。

TA貢獻1871條經驗 獲得超13個贊
如果您使用正則表達式沒有問題,則以下工作正常:
import re
file = open('file.xml', 'r').read()
pattern = r'name="(.*?)".*?<zip-code>(.*?)<\/zip-code>'
matches = re.findall(pattern, file, re.S)
for m in matches:
print("{} {}".format(m[0], m[1]))
并產生結果:
studio 14407
mailbox 33896
garage 33746
aystore 33746
添加回答
舉報