// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class XmlReplace {
    public static void main(String[] args) throws Exception {
        String s = "<stuff>\r\n" +
                   "<blabla/>\r\n" +
                   "<property name=\"hostName\" class=\"java.lang.String\">localhost</property>\r\n" +
                   "<property name=\"portNumber\" class=\"java.lang.Integer\">8080</property>\r\n" +
                   "<blabla/>\r\n" +
                   "</stuff>\r\n";
        OutputFormat fmt = new OutputFormat();
        fmt.setIndenting(true);
        XMLSerializer ser = new XMLSerializer(System.out, fmt);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(new StringReader(s)));
        ser.serialize(doc);
        XPathAPI.selectSingleNode(doc.getDocumentElement(), "//stuff/property[@name='hostName']/text()").setTextContent("Temp1");
        XPathAPI.selectSingleNode(doc.getDocumentElement(), "//stuff/property[@name='portNumber']/text()").setTextContent("Temp2");
        ser.serialize(doc);
    }
}
