看板 Python 關於我們 聯絡資訊
各位好 本人有類似以下的XML檔(output.xml)必須要用python來處理 希望可以擷取各個tag中的值 我的XML檔中有namespace,內容如下: <data xmlns="urn:ietf:params:ns:netconf:base:1.0"> <interfaces xmlns="http://namespace.net"> <interface> <name>Interface0</name> </interface> <interface> <name>Interface1</name> </interface> </interfaces> </data> 查了一下網路,有xml.etree這個library可以用 以下是我的code ------------------------------------ from xml.etree import cElementTree as ET tree = ET.ElementTree(file="output.xml") root = tree.getroot() nsmap = {'':'http://namespace.net'} # namespace for name in root.iterfind('./interfaces/interface/name', namespaces=nsmap): print(name.text) ----------------------------------------- 這個code是可以跑的,但自己希望可以進一步實現: 只抓取Interface1,也就是第二個interface中name的值 我嘗試過將'./interfaces/interface/name'改為'./interfaces/interface[2]/name' 不過這只有在XML中沒有namespace時,才能成功抓取到Interface1 請問各版友,有人知道對於有namespace的xml,如果有重複的tag 要如何只抓第k個tag中的值? 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 108.254.89.199 (美國) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1645518657.A.11A.html
OrzOGC: 這可以用BS吧? 02/22 20:28
VivianAnn: bs有嘗試,感覺比較慢 02/22 22:27
alvinlin: xmltodict 是 Python 中的一個模組 02/28 04:05
coeric: 我曾經使用xml去做 當我後來用bs4去做 真的覺得是新天地 03/09 17:47