简体   繁体   中英

Python: How to add a prefix to tags in an xml.etree.ElementTree

I use the python asciimathml library to parse some asciimathml and convert it to MathML

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

The only trouble is I need my tags with a m: prefix. How do I change above code so I get:

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

You can rename the tag, adding the 'm:' prefix:

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)

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM