the $q that you want to delete is the root element, i.e. the uppermost element in the document right below the document node. Deleting this would leave the
document empty and thus non-well-formed.
Delete the document node instead, i.e. do delete $q/…