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

时间:2011-03-03 16:09:29

标签: python xml

我使用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 个答案:

答案 0 :(得分: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>