Remove parent without removing children?

48 views
Skip to first unread message

Heck Lennon

unread,
Jul 9, 2024, 2:05:59 AM7/9/24
to beautifulsoup
Hello,

In the following KML file, I need to remove the MultiGeometry parent without removing the LineString children.

Does BS provide a function for that?

======
<MultiGeometry>
<LineString>
</LineString>
<LineString>
</LineString>
<LineString>
</LineString>
</MultiGeometry>
======

Thank you.

Chris Papademetrious

unread,
Jul 9, 2024, 6:05:10 AM7/9/24
to beautifulsoup
Hi frdt,

I think you want the Tag.unwrap() method. It replaces a tag in-place with its contents.

 - Chris

Heck Lennon

unread,
Jul 9, 2024, 6:48:51 AM7/9/24
to beautifulsoup
Right on! Thank you.

============
from bs4 import BeautifulSoup as BS
from pathlib import Path

INPUTFILE = "input.kml"
BASE = Path(INPUTFILE).stem
OUTPUTFILE = f"{BASE}.OUTPUT.kml"

with open(INPUTFILE, mode='rb') as file:
  fileContent = file.read()
soup = BS(fileContent, features="xml")

mg = soup.find('MultiGeometry') #if not found, check upper/lowercase
if mg:
newtag = mg.unwrap()
outp=open(OUTPUTFILE, 'w',encoding='utf-8')
outp.write(soup.prettify())
outp.close()      
else:
print("Not found")
============
Reply all
Reply to author
Forward
0 new messages