// 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.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

public class Replace {
    public static void main(String[] args) throws Exception {
        // load
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("C:\\replace.xml");
        // modify
        XPath xpath = XPathFactory.newInstance().newXPath();
        Node n = (Node)xpath.evaluate("//all[contains(aaa,'dig') and substring-after(ccc,'dig')='']/bbb[ccc='1']/ccc/text()", doc.getDocumentElement(), XPathConstants.NODE);
        if(n != null) {
            n.setTextContent("2");
        }
        // save
        DOMImplementation impl = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0");
        DOMImplementationLS feature = (DOMImplementationLS)impl.getFeature("LS","3.0");
        LSSerializer ser = feature.createLSSerializer();
        LSOutput output = feature.createLSOutput();
        output.setByteStream(new FileOutputStream("C:\\replace2.xml"));
        ser.write(doc, output); }
}
