I need to update an server.xml for Apache tomcat dynamically and add a new attribute and value.. This xml document has many elements with attributes with the same name. For Example multiple connector elements with different attribute values.
<Connector protocol="org.apache.coyote.http11.Http11NioProtocol"
port="${tomcat.http.port}"
connectionTimeout="${tomcat.connection.timeout}"
maxHttpHeaderSize="20480"
socket.soKeepAlive="true"
/>
<Connector protocol="org.apache.coyote.http11.Http11NioProtocol"
port="${tomcat.basic.https.port}"
socket.soKeepAlive="true"
SSLEnabled="true"
socket.appReadBufSize="17408"
scheme="https"
secure="true"
/>
I need to add a new attribute where connector in the element where the port value is ${tomcat.basic.https.port}.
This is what I got so far for finding the correct element.
DocumentBuilderFactory docFactory = buildDocFact();
DocumentBuilder docBuilder = null;
Document doc = null;
File file = new File(filePath);
docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse(file);
doc.getDocumentElement().normalize();
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes =
(NodeList) xpath.evaluate("//*[contains(@port,
'${tomcat.basic.https.port}')]", doc,
XPathConstants.NODESET);
for (int idx = 0; idx < nodes.getLength(); idx++)
{
Node value =
nodes.item(idx).getAttributes().getNamedItem("port");
String val = value.getNodeValue();
logger.info(val);
}
So the logger.info prints out the correct value so I know I am in the right element.
The question is how do i add append attribute and value to the end of this element?
There doesn't seem to be a create attribute function.
Once we can set the attrib and value, then I can easy save the results to a new xml doc.
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
Any ideas how I can append a new attribute and value?
I hope that made sense :)