// 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.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintStream;

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;

public class RenameNode {
    private static void print(PrintStream out, Document doc) throws IOException {
        OutputFormat fmt = new OutputFormat();
        fmt.setIndenting(true);
        XMLSerializer ser = new XMLSerializer(out, fmt);
        ser.serialize(doc);
    }
    public static void main(String[] args) throws Exception {
        String xml = "<doc><a>1</a><b>22</b><c>333</c></doc>";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));
        print(System.out, doc);
        doc.renameNode(XPathAPI.selectSingleNode(doc.getDocumentElement(), "/doc/b"), null, "b2");
        print(System.out, doc);
    }
}
