private static void updateMybatisXml(String url, String username, String password) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(false);
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmldoc = db.parse(xmlPath);
Element root = xmldoc.getDocumentElement();
Element per = (Element) selectSingleNode("/configuration/environments/environment/dataSource", root);
NodeList properties = per.getElementsByTagName("property");
Element urlElement = (Element) properties.item(1);
urlElement.setAttribute("value", url);
Element userNameElement = (Element) properties.item(2);
userNameElement.setAttribute("value", username);
Element passwordElement = (Element) properties.item(3);
passwordElement.setAttribute("value", password);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMImplementation domImpl = xmldoc.getImplementation();
DocumentType doctype = domImpl.createDocumentType("configuration",
"-//mybatis.org//DTD Config 3.0//EN",
"http://mybatis.org/dtd/mybatis-3-config.dtd");
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
transformer.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static Node selectSingleNode(String express, Element source) {
Node result = null;
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
System.out.println(result);
} catch (XPathExpressionException e) {
System.out.println(e.getMessage());
}
return result;
}