Python:如何在xml.etree.ElementTree中为标签添加前缀

0 投票
1 回答
1229 浏览
提问于 2025-04-16 12:56

我在用 Python 的 asciimathml 库来解析一些 asciimathml,并把它转换成 MathML。

>>> from xml.etree.ElementTree import tostring
>>> tostring(asciimathml.parse('sqrt 2'))
'<math><mstyle><msqrt><mn>2</mn></msqrt></mstyle></math>'

唯一的问题是,我需要我的标签前面加一个 m: 的前缀。我该怎么修改上面的代码,才能得到:

'<m:math><m:mstyle><m:msqrt><m:mn>2</m:mn></m:msqrt></m:mstyle></m:math>'

1 个回答

1

你可以给这个标签改个名字,加上'm:'这个前缀:

import asciimathml
from xml.etree.ElementTree import tostring

tree = asciimathml.parse('sqrt 2')
for elem in tree.getiterator():
    elem.tag = 'm:' + elem.tag

print tostring(tree)

结果是:

<m:math><m:mstyle><m:msqrt><m:mn>2</m:mn></m:msqrt></m:mstyle></m:math>

撰写回答