Search code examples
javaxpathxmlbeans

XPath selector for nodes that its ancestors are not a specific node


I'm writing an XPath selector to select all the node name o:OLEObject providing that its ancestor is not w:del. but the nodes in w:del are included in the result. Can you help me to clear it? Here is my script:

   publicList<String> getAllOleObjectId(XmlObject wobj) {
        List<String> lstOfOleObjIds = new ArrayList<String>();
        XmlCursor cursorForOle = wobj.newCursor();
        if(cursorForOle != null) {
            cursorForOle.selectPath(
                "declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' " + 
                "declare namespace o='urn:schemas-microsoft-com:office:office' " +
                ".//*/o:OLEObject[ancestor::*[not(self::w:del)]]"
            );
            while (cursorForOle.hasNextSelection()) {

                 cursorForOle.toNextSelection();
                 XmlObject oleObj = cursorForOle.getObject();
                 Node oleDomNode = oleObj.getDomNode();
                 NamedNodeMap domAttrObj = oleDomNode.getAttributes();
                 lstOfOleObjIds.add(domAttrObj.getNamedItem("r:id").getNodeValue());
           }
        }
        cursorForOle.dispose();
        return lstOfOleObjIds;
    }

Solution

  • You should replace your XPath with :

    //*/o:OLEObject[not(ancestor::w:del)]
    

    Select OLEObject element, child of any (*) element, and which has no ancestor element named del.