Java tutorial
import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; public class Main { public static void main(String[] args) throws Exception { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader("<root>\r\n" + // "<Users>\r\n" + // " <App id=\"test\">\r\n" + // " <Username>ADMIN</Username>\r\n" + // " <Password>ADMIN</Password>\r\n" + // " </App>\r\n" + // "</Users>\r\n" + // "<Users>\r\n" + // " <App id=\"test2\">\r\n" + // " <Username>ADMIN2</Username>\r\n" + // " <Password>ADMIN2</Password>\r\n" + // " </App>\r\n" + // "</Users>\r\n" + // "</root>"))); String inputId = "test2"; String xpathStr = "//Users/App[@id='" + inputId + "']"; // retrieve elements and change their content XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile(xpathStr + "/Username"); Node username = (Node) expr.evaluate(doc, XPathConstants.NODE); username.setTextContent("test-username"); expr = xpath.compile(xpathStr + "/Password"); Node password = (Node) expr.evaluate(doc, XPathConstants.NODE); password.setTextContent("test-password"); // output the document Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); System.out.println(writer.toString()); } }