[Patch #1094164] replaceChild(x,x) ends up removing x of the tree.  Add fix from Felix Rabe and a test case
diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py
index 4bb4ef4..84be99b 100644
--- a/Lib/xml/dom/minidom.py
+++ b/Lib/xml/dom/minidom.py
@@ -135,10 +135,10 @@
         if newChild.nodeType not in self._child_node_types:
             raise xml.dom.HierarchyRequestErr(
                 "%s cannot be child of %s" % (repr(newChild), repr(self)))
-        if newChild.parentNode is not None:
-            newChild.parentNode.removeChild(newChild)
         if newChild is oldChild:
             return
+        if newChild.parentNode is not None:
+            newChild.parentNode.removeChild(newChild)
         try:
             index = self.childNodes.index(oldChild)
         except ValueError: