为了账号安全,请及时绑定邮箱和手机立即绑定

使用 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 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信