XPathHandler { public String extractXml(String xpath, Object document) throws XPathExpressionException { try { final Document doc = transformToDocument(document); final Node node = (Node) XPathFactory.newInstance().newXPath().evaluate(xpath, doc, XPathConstants.NODE); Document newXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Node copyNode = newXmlDocument.importNode(node, true); newXmlDocument.appendChild(copyNode); return printXmlDocument(newXmlDocument); } catch (Exception e) { throw new RuntimeException(e); } }  String run(String xpath, Object document); String extractXml(String xpath, Object document);  }
@Test public void testExtractXml() throws Exception { XPathHandler xPathHandler = new XPathHandler(); String document = " <metadata>" + " <name>some name</name>" + " <steps>\n" + " <step>\n" + " <processor>\n" + " <name>Subset</name>\n" + " <version>1.0</version>\n" + " </processor>\n" + " <parameters>\n" + " <fullSwath>false</fullSwath>\n" + " <copyMetadata>false</copyMetadata>\n" + " <subSamplingX>1</subSamplingX>\n" + " <subSamplingY>1</subSamplingY>\n" + " </parameters>\n" + " </step>\n" + " <step>\n" + " <processor>\n" + " <name>Meris.CorrectRadiometry</name>\n" + " <version>1.1</version>\n" + " </processor>\n" + " <parameters>\n" + " <doRadToRefl>false</doRadToRefl>\n" + " <doCalibration>true</doCalibration>\n" + " <doSmile>true</doSmile>\n" + " <doEqualization>true</doEqualization>\n" + " <reproVersion>REPROCESSING_3</reproVersion>\n" + " </parameters>\n" + " </step>" + " </steps>" + "</metadata>"; String result1 = xPathHandler.extractXml(" final String expected1 = "" + "<step>\n" + " <processor>\n" + " <name>Subset</name>\n" + " <version>1.0</version>\n" + " </processor>\n" + " <parameters>\n" + " <fullSwath>false</fullSwath>\n" + " <copyMetadata>false</copyMetadata>\n" + " <subSamplingX>1</subSamplingX>\n" + " <subSamplingY>1</subSamplingY>\n" + " </parameters>\n" + " </step>"; assertEquals(expected1, result1); String result2 = xPathHandler.extractXml(" final String expected2 = "" + "<step>\n" + " <processor>\n" + " <name>Meris.CorrectRadiometry</name>\n" + " <version>1.1</version>\n" + " </processor>\n" + " <parameters>\n" + " <doRadToRefl>false</doRadToRefl>\n" + " <doCalibration>true</doCalibration>\n" + " <doSmile>true</doSmile>\n" + " <doEqualization>true</doEqualization>\n" + " <reproVersion>REPROCESSING_3</reproVersion>\n" + " </parameters>\n" + " </step>"; assertEquals(expected2, result2); }