[英]Changing an existing namespaced attribute with lxml
我有一個現有的 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 etree
pagexml = """<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
命名空間。
我對 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.