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.
Thank you.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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()) |