This currently only works for documents, is not tested and most likely will leak memory due to being recursive.