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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xpath.XPathAPI;

public class CreateAndCloneXPathExt {
    public static void main(String[] args) {
        try {
            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.newDocument();
            Element all = doc.createElement("all");
            doc.appendChild(all);
            ser.serialize(doc);
            Element one1 = doc.createElement("one");
            one1.appendChild(doc.createTextNode("A"));
            one1.setAttribute("a1", "0");
            one1.setAttribute("a2", "1");
            all.appendChild(one1);
            ser.serialize(doc);
            Element one1x = (Element)XPathAPI.selectSingleNode(doc.getDocumentElement(), "one[@a2='1']");
            Element one2 = (Element)one1x.cloneNode(true);
            one2.getFirstChild().setTextContent("BB");
            one2.setAttribute("a2", "2");
            all.appendChild(one2);
            ser.serialize(doc);
            Element one2x = (Element)XPathAPI.selectSingleNode(one2, ".");
            Element one3 = (Element)one2x.cloneNode(true);
            one3.getFirstChild().setTextContent("CCC");
            one3.setAttribute("a2", "3");
            all.appendChild(one3);
            ser.serialize(doc);
        } catch (FactoryConfigurationError e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return;
    }
}
