markijbema
markijbema

Reputation: 4055

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>'

Upvotes: 0

Views: 1241

Answers (1)

samplebias
samplebias

Reputation: 37909

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>

Upvotes: 1

Related Questions