ReplaceNode extends XpathMergeImpl { @Override public Document merge(Document original, Document newDoc) throws Exception { if (StringUtils.isEmpty(getXpathToNode())) { throw new Exception("No xpath node configured"); } Document resultDoc = original; Node node = createXPath().selectSingleNode(resultDoc, getXpathToNode()); if (node == null) { throw new Exception("Failed to resolve " + getXpathToNode()); } Node parent = node.getParentNode(); if (parent == null) { throw new Exception("Parent of " + getXpathToNode() + " is null"); } Node replacement = resultDoc.importNode(newDoc.getDocumentElement(), true); parent.replaceChild(replacement, node); return resultDoc; } ReplaceNode();  ReplaceNode(String xpath); @Override Document merge(Document original, Document newDoc); String getXpathToNode(); void setXpathToNode(String xpath);  }
@Test public void testReplaceNodeDoesNotExist() throws Exception { ReplaceNode rn = new ReplaceNode("/Root/NonExistentNode"); Document original = XmlHelper.createDocument(ORIGINAL); Document newDoc = XmlHelper.createDocument(REPLACEMENT); try { Document merged = rn.merge(original, newDoc); fail("merge should fail with non-existent node"); } catch (Exception expected) { assertNotNull(expected.getMessage()); assertTrue(expected.getMessage().matches(".*Failed to resolve.*")); } }