What is the proper way to automate use of ElementTree in Python?

Mypebypefaw

New Member
I am using Python to generate some XML files which are used by another device. I have a solution which works but I am trying to improve it. One of the things which the XML must contain is a schedule. Here is what the entry for Monday should look like in XML.\[code\]<Monday open="08:00" close="17:00" />\[/code\]I have no problems generating this with ElementTree in Python but right now I am stuck having a line of code for each day. So a snippet of my Python code looks like this:\[code\]SubElement(schedule, 'Monday', open='08:00', close='17:00')SubElement(schedule, 'Tuesday', open='08:00', close='17:00')...SubElement(schedule, 'Sunday', open='08:00', close='17:00')\[/code\]The XML file will wind up having multiple schedules in it and typing all of that out seems needlessly repetitive. Instead of this I wanted to create a function which iterates over a list to build up the parameters to pass to SubElement. As part of that function I created this string to replace the times in my SubElement call. \[code\]"open=" + "\'08:00\'" + ", " + "close=" + "\'17:00\'"\[/code\]If I print this out it looks identical to what I pass to SubElement when I type out the code the long way. However it clearly isn't the same as I get the following error when I try to run the script.\[code\]File "C:\Python27\lib\xml\etree\ElementTree.py", line 528, in SubElement attrib = attrib.copy()AttributeError: 'str' object has no attribute 'copy'\[/code\]I have looked at the SubElement code and it seems to be expecting a dictionary. However, when I type things out the long way I don't appear to be supplying a dictionary as input then either so I can't see why the function should accept that input but not the string which appears, to me, to be equivalent. Is there any way to do what I am trying to do or am I stuck with a lot of repetitive lines of code?
 
Back
Top