bernabegh
2/5/2019 - 4:29 PM

get field from XML java XPath

private String getFieldFromXML(String xml,String fieldToFind){
        //http://www.baeldung.com/java-xpath
        String found;
        try{
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(fieldToFind);
            NodeList nl = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
            found=nl.item(0).getTextContent();
        }catch (Exception e){
            found=null;
        }
        return found;
    }