I am trying to format the following xml
<block formula="MY_VAR < 3"><set-variable name="OTHER_VAR"></set-variable></block>
into
<block formula="MY_VAR < 3">
<set-variable name="OTHER_VAR">
</set-variable>
</block>
using xmlformatter and getting an error because of the < in my formula. Specifically the error is
ExpatError: not well-formed (invalid token)
when I try the code
my_xml = '<block formula="MY_VAR < 3"><set-variable name="OTHER_VAR"></set-variable></block>'
formatter = xmlformatter.Formatter(indent="1", indent_char=" ", encoding_output="UTF-8", preserve=["literal"])
pretty_xml = formatter.format_string(my_xml)
How do I include the less than in my formula and be able to format my XML?
You can use xml.sax.saxutils.quoteattr to escape the attribute value when constructing the xml string.
If you don't control construction of the xml this hack will fix the xml in the example: