亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Python 中具有不同標簽的子項解析 XML

使用 Python 中具有不同標簽的子項解析 XML

阿晨1998 2022-12-27 15:47:19
我正在嘗試使用 python 解析文件中的以下 xml 數據,以便僅打印帶有標簽“zip-code”及其屬性名稱的元素<response status="success" code="19"><result total-count="1" count="1">  <address>    <entry name="studio">      <zip-code>14407</zip-code>      <description>Nothing</description>    </entry>    <entry name="mailbox">      <zip-code>33896</zip-code>      <description>Nothing</description>    </entry>    <entry name="garage">      <zip-code>33746</zip-code>      <description>Tony garage</description>    </entry>    <entry name="playstore">      <url>playstation.com</url>      <description>game download</description>    </entry>    <entry name="gym">      <zip-code>33746</zip-code>      <description>Getronics NOC subnet 2</description>    </entry>    <entry name="e-cigars">      <url>vape.com/24</url>      <description>vape juices</description>    </entry>   </address></result></response>我要運行的 python 代碼是from xml.etree import ElementTree as ETtree = ET.parse('file.xml')root = tree.getroot()items = root.iter('entry')for item in items:    zip = item.find('zip-code').text    names = (item.attrib)    print(' {} {} '.format(        names, zip    ))但是,一旦到達沒有“郵政編碼”標簽的項目,它就會失敗。我怎么能跑這個?提前致謝
查看完整描述

3 回答

?
慕姐4208626

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'}


查看完整回答
反對 回復 2022-12-27
?
三國紛爭

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是個問題。


查看完整回答
反對 回復 2022-12-27
?
慕桂英4014372

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


查看完整回答
反對 回復 2022-12-27
  • 3 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號