home ~ socials ~ projects ~ rss

Remove an XML Declaration with BeautifulSoup in Python

October 2025
from bs4 import BeautifulSoup

input = """
  <?xml version="1.0" encoding="UTF-8"?>
  <svg></svg>
"""

soup = BeautifulSoup(input, 'xml')
output = soup.find("svg")
print(output)
Output:
<svg/>
Head's up

The lxml package must be installed for BeautifulSoupt to use. It doesn't need to be imported directly, but has to be on the system.

end of line
Share link:
https://www.alanwsmith.com/en/33/zw/1y/pp/?remove-an-xml-declaration-with-beautifulsoup-in-python