我有一个现有的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名称空间。
发布于 2020-09-25 06:24:44
我不熟悉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>https://stackoverflow.com/questions/64055063
复制相似问题