[Tutor] Basic ElementTree xml question
Peter Otten
__peter__ at web.de
Mon Feb 24 03:00:45 EST 2020
Phil wrote:
> Thank you for reading this,
>
> I'm trying to create an xml file with an output that looks like this"
>
> <gpx>
>
> <wpt lat="-32.506533000" lon="137.740017000">
>
> and this is the closest that I have so far achieved:
>
> <gpx>
>
> <wpt>
>
> with this code snippet:
>
> from xml.etree import ElementTree as ET
>
> gpx = ET.Element("gpx")
>
> wpt = ET.SubElement(gpx, "wpt")
>
> So my question is, how to I include the lat and lon text after <wpt ?
>>> gpx = ET.Element("gpx")
>>> wpt = ET.SubElement(gpx, "wpt", lat="-32.5", lon="137.7")
>>> ET.tostring(gpx)
b'<gpx><wpt lat="-32.5" lon="137.7" /></gpx>'
If that's not possible:
>>> wpt.attrib["not-a-valid-python-identifier"] = "spam"
>>> ET.tostring(gpx)
b'<gpx><wpt lat="-32.5" lon="137.7" not-a-valid-python-identifier="spam"
/></gpx>'
or
>>> ET.tostring(ET.Element("foo", attrib={"ham-spam": "jam", "foo-bar":
"baz"}))
b'<foo foo-bar="baz" ham-spam="jam" />'
PS:
> I've searched the Internet for example code but haven't found anything
> that allows strings after "<wpt ". So far, I haven't been able to turn
> the information in the Etree manual into anything close to what I need.
Goggling for "create elementtree element with attribute" finds
https://stackoverflow.com/questions/25807414/how-do-i-add-attributes-to-subelement-in-elementtree-python
More information about the Tutor
mailing list