[Tutor] Basic ElementTree - another question
Don Jennings
dfjennings at gmail.com
Thu Feb 27 18:06:55 EST 2020
> On Feb 27, 2020, at 12:44 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
>
> On 27/02/2020 05:59, Phil wrote:
>
>> <gpx>
>>
>> <wpt lat="-32.506533000" lon="137.740017000">
>> <name>1</name>
>> </wpt>
>> </gpx>
>>
>> and this is what I've currently got:
>>
>> <gpx>
>> <wpt lat="-32.506533000" lon="137.740017000" />
>> <name name="1" />
>> </gpx>
>>
>> This is the code that generates the above file:
>>
>> from xml.etree import ElementTree as ET
>>
>> gpx = ET.Element("gpx")
>>
>> wpt = ET.SubElement(gpx, "wpt", lat="-32.506533000", lon=
>> "137.740017000")
>> name = ET.SubElement(gpx, "name", name="1")
>
> Notice you said name was a sub-element of gpx.
> That's what you got. But you want name to be a
> sub-element of wpt…
Adding to what Alan wrote, notice that you added the keyword argument name=“1”, so you get it as an attribute of the element <name>; however, what you want is for it to be the content of the element. In the latter case, assign it to the text attribute of the element as Peter pointed out:
first = SubElement(e, "first")
first.text = "1st child”
Try fixing those 2 things, then post back your code if you run into difficulty, thanks.
Best,
Don
More information about the Tutor
mailing list