[Tutor] Basic ElementTree - another question

Peter Otten __peter__ at web.de
Wed Feb 26 03:50:00 EST 2020


Phil wrote:

> On 25/2/20 10:04 pm, Don Jennings wrote:
> 
>> Please paste the code which you’ve tried, so we can see what’s happening,
>> thanks.
> 
> I'm a little embarrassed

Don't be.

> to say, Don, that I cannot relate the example
> that you provided with what I'm trying to achieve. I cannot get past the
> code snippet that I showed when I first asked my question and I cannot
> make hear nor tail of the ElementTree manual. In short, I'm at a total
> loss.

Basic xml consists of nodes

    xml:

    <stuff>...</stuff>

    (an empty node can also be written <stuff/>)

    etree:

    Element("stuff")

that can have attributes

    xml:

    <stuff foo="bar", ham="spam">...</stuff>  

    etree:

    Element("stuff", foo="bar" ham="spam") 

that can include text

    xml:

    <stuff>yadda</stuff>

    etree:

    e = Element("stuff")
    e.text = "yadda"

or children

    <stuff><first>1st child</first><second>whatever</second></stuff>

    e = Element("stuff")

    first = SubElement(e, "first")
    first.text = "1st child"

    second = SubElement(e, "second")
    second.text = "whatever"

These building blocks should be enough to generate the desired xml.

If you find that too hard, and if you want to learn Python rather than have 
someone else solve your current problem it's probably better to step back 
and work through a Python tutorial, tackle some basic problems (we'll be 
happy to help with those, too) and revisit xml generation with element tree 
once you are a bit more comfortable with the language.


PS: Regarding element tree I like lxml and its documentation

https://lxml.de/tutorial.html

but as there are differences between lxml and the stdlib I'm not sure 
whether you will get even more confused if you read it right now.



More information about the Tutor mailing list