0

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 :)

1 Answer 1

1

You can try ((Element)node).setAttribute("attributeName", "value");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.