如何使用 LXML 獲取和設定屬性的值已經有很好的記錄,但是有沒有辦法重命名現有屬性的名稱?
目標是從
<element old="cheese"/>
到
<element new="cheese"/>
我目前正在做的事情有點復雜——洗掉屬性,然后用新名稱和舊值重新添加它:
from io import StringIO
from lxml import etree
doc = StringIO('<element old="cheese"/>')
tree = etree.parse(doc)
elem = tree.getroot()
attr_value = elem.attrib['old']
del elem.attrib['old']
elem.attrib['new'] = attr_value
有沒有辦法直接重命名屬性而不是使用新鍵洗掉和重新添加?
uj5u.com熱心網友回復:
下面對 python “開箱即用” python xml lib - ElementTree執行相同的操作。
import xml.etree.ElementTree as ET
xml = '''<element old="cheese"/>'''
root = ET.fromstring(xml)
root.attrib['new'] = root.attrib.pop('old')
ET.dump(root)
輸出
<element new="cheese" />
uj5u.com熱心網友回復:
首先,我希望我可以兩次投票贊成您的問題,因為您提供了一個最小的、可復制的示例,我可以復制/粘貼/運行。那些剛接觸堆疊溢位的人應該注意!我想這是因為與你和我一樣長的用戶不會問那么多問題。
我不認為你在做什么是令人費解的,但既然.attrib是一個 dict 你可以做這樣的事情來代替:
elem.attrib['new'] = elem.attrib.pop('old')
完整示例:
from io import StringIO
from lxml import etree
doc = StringIO('<element old="cheese"/>')
tree = etree.parse(doc)
elem = tree.getroot()
elem.attrib['new'] = elem.attrib.pop('old')
print(etree.tostring(tree).decode())
列印輸出...
<element new="cheese"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459336.html
