Sep-03-2022, 07:31 PM
Hello,
I read BS's documentation, but can't figure out something very simple: Find if an element exists at a specific location in the tree; If it exists, change its text; If it doesn't, insert it right below the parent.
I read BS's documentation, but can't figure out something very simple: Find if an element exists at a specific location in the tree; If it exists, change its text; If it doesn't, insert it right below the parent.
from bs4 import BeautifulSoup """ <?xml version="1.0" encoding="utf-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Document> <name> EDIT ME </name> </Document> </kml> """ soup = BeautifulSoup(open('input.kml', 'r'), 'xml') #BAD name = soup.kml.Document.name name = soup.select('kml > Document > name') if name: print("Found") name.string="New name" #no change ! name.string.replace_with("New name") #Error else: print("Not found") name = soup.new_tag("name") name.string = "New tag" #doc= soup.kml.Document #doc = soup.select('kml.Document') doc = soup.select('kml > Document') doc.append(name) #No change ! print(soup.prettify())Thank you.