Complete refactor to copy nodes to a separate DomDocument instead of trying to rearrange them in an existing one.