Reputation: 11
I am trying to write an XML file to disk using this function:
def modify_xml(input_file_xml, output_file_xml, input_file_names, output_path, output_format, params_sub_nodes = {}):
tree = ET.parse(input_file_xml)
root = tree.getroot()
if len(input_file_names) == 1:
file_node_input = root.find('node[@id="Read"]/parameters/file')
elif len(input_file_names) == 2:
file_node_input = root.find('node[@id="ProductSet-Reader"]/parameters/fileList')
else:
raise Exception('number of files equal to: %s not supported !' %str(len(input_file_names)))
file_node_input.text = ','.join(input_file_names)
file_node_output_name = root.find('node[@id="Write"]/parameters/file')
file_node_output_name.text = output_path
file_node_output_format = root.find('node[@id="Write"]/parameters/formatName')
file_node_output_format.text = output_format
for sub_node_name, sub_node_content in params_sub_nodes.items():
sub_node = root.find(sub_node_name)
sub_node.text = sub_node_content
print(output_file_xml)
print(type(output_file_xml))
tree.write(output_file_xml)
But I get the following TypeError:
in modify_xml
tree.write(output_file_xml)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 776, in write
short_empty_elements=short_empty_elements)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 941, in _serialize_xml
short_empty_elements=short_empty_elements)
File "/usr/lib/python3.6/xml/etree/ElementTree.py", line 938, in _serialize_xml
write(_escape_cdata(text))
TypeError: write() argument must be str, not tuple
even if, when printing output_file_xml and its type (the 3 last lines in my function), I get that it's a string:
/tmp/filter_edited.xml
<class 'str'>
The XML is also created and saved in the specified output_path even if the program crashs because of this error What do you think I am missing here?
Upvotes: 0
Views: 518
Reputation: 11
After thoroughly debugging my code, I found the problem's cause.
When setting a breakpoint at line 938 of /usr/lib/python3.6/xml/etree/ElementTree.py, and visualizing the types of the elements inserted in the tree (text variable in _serialize_xml function) one by one, it turns out thet one of them was a tuple.
This is due to a comma that I mistakingly added at the end of output_path variable when calling the modify_xml function, which converted the string to a tuple
file_node_output_name.text = output_path
It's a pity the error message was not very much expressive ! I mean, when reading this Error:
TypeError: write() argument must be str, not tuple
The first thing that comes to one's mind is that there is a type error in the XML's output path(write's function argument) and not in the text inserted in the XML itself...
Upvotes: 1