Python Forum

Full Version: [SOLVED] [BS] Why new tag only added at the end when defined outside the loop?
You're currently viewing a stripped down version of our content. View the full version with proper 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:

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.
(Sep-04-2022, 10:50 PM)Winfried Wrote: [ -> ]I notice it will only be added in the last Placemark when defined before entering the loop
It will only add stuff to last element in loop if you not insert to something that is defined before the loop.
from bs4 import BeautifulSoup

"""
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
 <Document>
    <Placemark>
    hello
    </Placemark>
    <Placemark>
    </Placemark>
 </Document>
</kml>
"""

soup = BeautifulSoup(open('pla.kml'), 'xml')
mark = soup.find_all('Placemark')
for item in mark:
    item.string = 'world'
>>> soup
<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Placemark>world</Placemark>
<Placemark>world</Placemark>
</Document>
</kml>
Don't add [SOLVED] if is not that,do not add anything other that the Title is best.