Search code examples
javaxmldom4j

Dom4j: wrap all elements with <any> tags


 public static void paintAllNodes(org.w3c.dom.Document domDocument) {
        DOMReader reader = new DOMReader();
        org.dom4j.Document dom4jdoc = reader.read(domDocument);

    }

Basically, I would like to use //* xpath to select all elements, and wrap <any> element tags around every single elements.


Solution

  • This is my code which uses xpath expression //* to avoid recursion as you've requested:

    public static void main(String[] args) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        String xml = "<html><head><title>title</title></head><body><h1>title</h1></body></html>";
        Document document = saxReader.read(new StringReader(xml));
    
        List nodes = document.selectNodes("//*");
        for (Iterator<Node> iterator = nodes.iterator(); iterator.hasNext();) {
            Node currentNode = iterator.next();
            DefaultElement newElement = new DefaultElement("any");
            Element parent = currentNode.getParent();
            if (parent != null) {
                List contentList = parent.content();
                int index = contentList.indexOf(currentNode);
                parent.remove(currentNode);
                newElement.add(currentNode);
                contentList.add(index, newElement);
            }
        }
    
        Element rootElement = document.getRootElement();
        DefaultElement newRootElement = new DefaultElement("any");
        document.setRootElement(newRootElement);
        newRootElement.add(rootElement);
        System.out.println(document.asXML());
    }
    

    This is my output:

    <?xml version="1.0" encoding="UTF-8"?>
    <any><html><any><head><any><title>title</title></any></head></any><any><body><any><h1>title</h1></any></body></any></html></any>
    

    Hope this helps.