xmltodict
xmltodict copied to clipboard
cdata value as integer generates TypeError
Using xmltodict
on RedHat runs like a charm. However, moving the exact same script to Alpine has generated an issue in the particular use case where the cdata
value is an integer.
I reproduced the issue by using the yq
tool (https://github.com/kislyuk/yq) that transforms a yaml input into a XML output, using xmltodict
. My yaml input is quite simple:
test:
element:
'@id': 10
'#': 10
Once given to yq
(and thus xmltodict
), I'm expecting an output similar to:
<test>
<element id="10">10</element>
</test>
(I'm using #
as cdata_key
instead of the default #text
, but this is not changing the game)
However, I have the following output and exception:
<test>
<element id="10">TypeError: coercing to Unicode: need string or buffer, int found.
The attribute with an integer value is correctly handled and becomes the id="10"
string, but the element value as an integer generates the error.
More precisely, that's line 415 (https://github.com/martinblech/xmltodict/blob/master/xmltodict.py#L415) of xmltodict
that generates the error... on Alpine (and for example, not on RedHat !... but don't ask me why!): the characters
method of the Handler is expecting a string, and an integer is provided => TypeError!
The bugfix is quite simple and efficient: force the data to be a string with the str( )
so that the line 415 becomes:
content_handler.characters(str(cdata))
I would be happy to provide a Pull Request with this change if you are ok with that update.
Thanks for your help, and great thanks for your work !
{
"test": {
"element": {
"-id": "10",
"#text": 10
}
},
"#omit-xml-declaration": "yes"
}
may be converted to
<test>
<element id="10" number="true">10</element>
</test>