我有一個現有的 XML 文檔,我想將命名空間屬性更改為另一個值。我有這個:<ac:structured-macro ac:name="center"> <ac:rich-text-body> <p> some text </p> </ac:rich-text-body></ac:structured-macro>我想把上面的變成這樣:<ac:structured-macro ac:name="new_center"> <ac:rich-text-body> <p> some text </p> </ac:rich-text-body></ac:structured-macro>這個Python代碼:from lxml import etreepagexml = """<ac:structured-macro ac:name="center"> <ac:rich-text-body> <p> some text </p> </ac:rich-text-body> </ac:structured> -macro>"""prefix_map = {"ac": "http://www.atlassian.com/schema/confluence/4/ac/", "ri": "http://www.atlassian.com/schema/confluence/4/ri/"}parser = etree.XMLParser(recover=True)root = etree.fromstring(pagexml, parser)for action, elem in etree.iterwalk(root, events=("end",)): if elem.tag == "ac:structured-macro": if elem.get("ac:name") == "center": elem.set("{ac}name", "new_center")print(etree.tostring(root, pretty_print=True, encoding=str))產生這個:<ac:structured-macro xmlns:ns0="ac" ac:name="center" ns0:name="new_center"> <ac:rich-text-body> <p> some text </p> </ac:rich-text-body></ac:structured-macro>可以<ac:structured-macro>存在于 XML 樹中的任何位置。我知道我可以使用正則表達式來做到這一點,但我更愿意以正確的方式做到這一點,因為我認為這會更強大。我希望在某個地方我可以傳遞prefix_map并讓它尊重ac命名空間。
1 回答

jeck貓
TA貢獻1909條經驗 獲得超7個贊
我對 lxml 不熟悉。這里還有一個解決方案,僅供大家參考。
from simplified_scrapy import SimplifiedDoc
html = '''
<ac:structured-macro ac:name="center">
<ac:rich-text-body>
<p>
some text
</p>
</ac:rich-text-body>
</ac:structured-macro>
'''
doc = SimplifiedDoc(html)
structuredMacro = doc.select('ac:structured-macro')
structuredMacro.setAttr('ac:name', 'new_center')
# Or
# structuredMacro.setAttrs({'ac:name': 'new_center'})
print(doc.html)
結果:
<ac:structured-macro ac:name="new_center">
<ac:rich-text-body>
<p>
some text
</p>
</ac:rich-text-body>
</ac:structured-macro>
添加回答
舉報
0/150
提交
取消