You may want to take a look at the extras in sigil_bs4 versus normal bs4.
See:
https://github.com/Sigil-Ebook/Sigil...s4/__init__.py
For "serialize_xhtml" near line 470 which tries to rebuild the source as close as possible to what was parsed, similar to how Sigil itself does it.