Sep-04-2022, 10:50 PM
(This post was last modified: Sep-04-2022, 10:50 PM by Winfried.
Edit Reason: Formatting
)
Hello,
I need to add a new tag in all Placemark blocks in a KML file.
I notice it will only be added in the last Placemark when defined before entering the loop, while it works as expected if defined (needlessly) within the loop again and again:
Any idea why?
Thank you.
Here's what I get after running the script:
Edit: The explanation is that a tag is unique, with references to the next and previous elements in the tree. So a fresh new tag is needed at every turn of the loop.
I need to add a new tag in all Placemark blocks in a KML file.
I notice it will only be added in the last Placemark when defined before entering the loop, while it works as expected if defined (needlessly) within the loop again and again:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("input.kml", 'r'), 'xml')
#Add element to all Placemarks
tag = soup.new_tag("i")
tag.string = "Don't"
for pm in soup.find_all("Placemark"):
#works
pm.coordinates.string="blah"
#Works if re-create tag in the loop
#tag = soup.new_tag("i")
#tag.string = "Don't"
#append/insert: only adds to last pm when tag defined outside loop!
#pm.append(tag)
pm.insert(0,tag)
#Shows things look good
#print(pm.prettify())
print(soup.prettify())print(pm.prettify()) within the loop shows things look like expected.Any idea why?
Thank you.
Here's what I get after running the script:
Output:<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>
Document.kml
</name>
<Placemark>
<name>
Document Feature 1
</name>
</Placemark>
<Placemark>
<name>
Document Feature 2
</name>
</Placemark>
<Placemark>
<i>
Don't
</i>
<name>
My track
</name>
<LineString>
<coordinates>
-0.376291,43.296237,199.75
-0.377381,43.29405
</coordinates>
</LineString>
</Placemark>
</Document>
</kml>---Edit: The explanation is that a tag is unique, with references to the next and previous elements in the tree. So a fresh new tag is needed at every turn of the loop.
