Why is there no functional xml?
Peter Otten
__peter__ at web.de
Tue Jan 23 09:52:58 EST 2018
Rustom Mody wrote:
> Its obviously easier in python to put optional/vararg parameters on the
> right side rather than on the left of a parameter list.
> But its not impossible to get it in the desired order — one just has to
> 'hand-parse' the parameter list received as a *param
> Thusly:
> appointments = E.appointments(
> {"reminder":"15"},
> E.appointment(
> E.begin(1181251680),
> E.uid("040000008200E000"),
> E.alarmTime(1181572063),
> E.state(),
> E.location(),
> E.duration(1800),
> E.subject("Bring pizza home")
> )
> )
Let's not waste too much effort on minor aesthic improvements ;)
>> Personally I'd probably avoid the extra layer and write a function that
>> directly maps dataclasses or database records to xml using the
>> conventional elementtree API.
>
> I dont understand…
> [I find the OO/imperative style of making a half-done node and then
> [throwing
> piece-by-piece of contents in/at it highly aggravating]
What I meant is that once you throw a bit of introspection at it much of the
tedium vanishes. Here's what might become of the DOM-creation as part of an
actual script:
import xml.etree.ElementTree as xml
from collections import namedtuple
Appointment = namedtuple(
"Appointment",
"begin uid alarmTime state location duration subject"
)
appointments = [
Appointment(
begin=1181251680,
uid="040000008200E000",
alarmTime=1181572063,
state=None,
location=None,
duration=1800,
subject="Bring pizza home"
)
]
def create_dom(appointments, reminder):
node = xml.Element("zAppointments", reminder=str(reminder))
for appointment in appointments:
for name, value in zip(appointment._fields, appointment):
child = xml.SubElement(node, name)
if value is not None:
child.text = str(value)
return node
with open("appt.xml", "wb") as outstream:
root = create_dom(appointments, 15)
xml.ElementTree(root).write(outstream)
To generalize that to handle arbitrarily nested lists and namedtuples a bit
more effort is needed, but I can't see where lxml.objectify could make that
much easier.
More information about the Python-list
mailing list