[Tutor] Basic ElementTree - another question

Don Jennings dfjennings at gmail.com
Mon Feb 24 21:30:37 EST 2020


> On Feb 24, 2020, at 7:54 PM, Phil <phillor9 at gmail.com> wrote:
> 
> On 24/2/20 6:30 pm, Peter Otten wrote:
> 
> I thought that I would now be able to proceed to the next step but unfortunately that's not the case despite extensive Internet searching.
> 
> This is what I want to achieve:
> 
>   <wpt lat="-32.506533000" lon="137.740017000">
>     <name>1</name>
>     <cmt>1</cmt>
>     <desc>1</desc>
>   </wpt>
> 
> and then repeat as above to the next destination, with a different name.
> 
> This gives me the first line but, of course, the next line is not correct.
> 
>   gpx = ET.Element("gpx")
> 
>   wpt = ET.SubElement(gpx, "wpt", lat="-32.506533000", lon= "137.740017000")
>   ET.SubElement(wpt, "name=1”)

Hi, Phil. When you add keyword arguments (e.g. lat and lon), those become attributes in the resulting start-tag(s). Instead, assign the value to the text attribute of the element:

>>> import xml.etree.ElementTree as ET
>>> root = ET.Element("root")
>>> child = ET.SubElement(root, "child", attr="some attribute")
>>> child.text = “content"
>>> ET.tostring(root)
b'<root><child attr="some attribute">content</child></root>’

Best,
Don




More information about the Tutor mailing list