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

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

使用 lxml 更改現有命名空間屬性

使用 lxml 更改現有命名空間屬性

小怪獸愛吃肉 2023-09-05 20:27:52
我有一個現有的 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>


查看完整回答
反對 回復 2023-09-05
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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