public static Object evaluateXPath(String xml, String xpath, QName returnType) throws XPathExpressionException, SAXException { if (null == xpath) return null; Document document = null; try { document = getXmlDocumentBuilder().parse(new ByteArrayInputStream (xml.getBytes(StandardCharsets.UTF_8))); } catch (UnsupportedEncodingException e1) { throw new RuntimeException("Totally weird UTF-8 exception", e1); } catch (IOException e2) { throw new RuntimeException("Totally weird io exception", e2); } xpath = xpath.trim(); return getXpath().evaluate(xpath.trim(), document, returnType); }
/** * A helper method which validates a String against an array of XPath test * strings. * * @param xml The xml String to validate * @param tests Array of XPath strings to test (in boolean mode) on the xml * @return null if all good, otherwise the first test that fails. */ public static String validateXPath(String xml, String... tests) throws XPathExpressionException, SAXException { if (tests==null || tests.length == 0) return null; Document document = null; try { document = getXmlDocumentBuilder().parse(new ByteArrayInputStream (xml.getBytes(StandardCharsets.UTF_8))); } catch (UnsupportedEncodingException e1) { throw new RuntimeException("Totally weird UTF-8 exception", e1); } catch (IOException e2) { throw new RuntimeException("Totally weird io exception", e2); } for (String xp : tests) { xp=xp.trim(); Boolean bool = (Boolean) getXpath().evaluate(xp, document, XPathConstants.BOOLEAN); if (!bool) { return xp; } } return null; }