When removing a DTD node, it must not be added to a document fragment. Otherwise it will leak. Also make sure that removed attributes aren't added to document fragments.
When inserting a DTD node, make sure that the 'intSubset' member of the document struct is updated and the previous DTD is unlinked and freed. This fixes memory leaks and potential segfaults. See RT #80521: