Search code examples
javaxmldom4j

add node to a node XML dom4j


In DOM4J and XML how to add a node to an existing node?

If I follow the example its very easy and works great if I have an element already.

Element root = doc.getRootElement();
Element someElement = root.addElement("some");
Element anotherElement = someElement.addElement("another");

and so forth. Easy if I have an Element object.

but once I lose a reference or am loading an xml and not creating one from scratch I just can't wrap my head around how I add a node /element exactly where I want.

So the specific question is: Given a document and an specific element in it, how do I add an element underneath it? Do I have to iterate through the whole document? Xpath I can only get to return nodes which have no .addElement and I can't turn it into an element. Im simply stumped and aside from adding an ID=? to every single node I just cant figure out how to put something exactly where I want it to go. Any help or direction would be greatly appreciated.


Solution

  • You can either iterate and check the required node and add the newly created node to it or you can use and xpath expression to get the particular node and add new node to it.

    Iteration:

        public void iterateNodes() {
         SAXReader reader = new SAXReader();
         Document document = reader.read("yourxml.xml");
         Element root = document.getRootElement();
         for ( Iterator i = root.elementIterator(); i.hasNext(); ){
               Element row = (Element) i.next();
               Iterator itr = row.elementIterator();
               while(itr.hasNext()) {
                    Element child = (Element) itr.next();
                    String name = child.getQualifiedName();
                    if(name.equals("requiredName") {
                       //create node and add it to child.
                    }   
               }
         }
     }
    

    XPath:

    public void addNodeUsingXpath() {
        SAXReader reader = new SAXReader();
         Document document = reader.read("yourxml.xml");
            String xpathExpression = "yourxpath";
            List<Node> nodes = document.selectNodes(xpathExpression);
            // nodes will have all the child nodes under your Xpath.
            for (Node node : nodes) {
               //get the required node and add your new node to specific node.
                if(node instanceof Element) {
                     Element e = (Element) node;
                     e.addElement("newElement");
                     ....
                }
            }
    }