class XmlTool {

    public static Optional<String> modifyElement(String xml, String elementTag, String newValue)
            throws IOException, TransformerException, ParserConfigurationException, SAXException {

        if (xml == null || xml.isEmpty()) {
            // no XML content to be modified, return empty
            return Optional.empty();
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setNamespaceAware(true);
        dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        DocumentBuilder db = dbFactory.newDocumentBuilder();
        InputSource source = new InputSource(new StringReader(xml));
        Document doc = db.parse(source);

        Node modNode = doc.getElementsByTagName(elementTag).item(0);
        if (modNode == null) {
            // did not find the specified element to be modified, return empty
            // System.out.println("Did not find element tag " + elementTag + " in XML");
            return Optional.empty();
        } else {
            modNode.setTextContent(newValue);
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        // return the modified String representation of the XML
        return Optional.of(writer.toString().trim());
    }

    private  XmlTool();

}