class XModifier {

    private void create(Node parent, XModifyNode node) throws XPathExpressionException {
        Node newNode;
        if (node.isAttributeModifier()) {
            //attribute
            createAttributeByXPath(parent, node.getCurNode().substring(1), node.getValue());
        } else {
            //element
            if (node.isRootNode()) {
                //root node
                newNode = parent;
                boolean canMoveToNext = node.moveNext();
                if (!canMoveToNext) {
                    //last node
                    newNode.setTextContent(node.getValue());
                } else {
                    //next node
                    create(newNode, node);
                }
            } else if (node.getCurNode().equals("text()")) {
                parent.setTextContent(node.getValue());
            } else {
                //element
                findOrCreateElement(parent, node);
            }
        }

    }

}

class XModifierTest {

    @Test
    public void create() throws ParserConfigurationException, IOException, SAXException {

        Document document = createDocument();
        Document documentExpected = readDocument("createExpected.xml");
        XModifier modifier = new XModifier(document);
        modifier.setNamespace("ns", "http://localhost");
        // create an empty element
        modifier.addModify("/ns:root/ns:element1");
        // create an element with attribute
        modifier.addModify("/ns:root/ns:element2[@attr=1]");
        // append an new element to existing element1
        modifier.addModify("/ns:root/ns:element1/ns:element11");
        // create an element with text
        modifier.addModify("/ns:root/ns:element3", "TEXT");
        modifier.modify();
        assertXmlEquals(documentExpected, document);
    }

}