public static boolean protectAgainstWrappingAttack(Node startNode,String value){
  Node startParent=startNode.getParentNode();
  Node processedNode=null;
  Element foundElement=null;
  String id=value.trim();
  if (!id.isEmpty() && id.charAt(0) == '#') {
    id=id.substring(1);
  }
  while (startNode != null) {
    if (startNode.getNodeType() == Node.ELEMENT_NODE) {
      Element se=(Element)startNode;
      NamedNodeMap attributes=se.getAttributes();
      if (attributes != null) {
        for (int i=0; i < attributes.getLength(); i++) {
          Attr attr=(Attr)attributes.item(i);
          if (attr.isId() && id.equals(attr.getValue())) {
            if (foundElement == null) {
              foundElement=attr.getOwnerElement();
            }
 else {
              log.log(java.util.logging.Level.FINE,"Multiple elements with the same 'Id' attribute value!");
              return false;
            }
          }
        }
      }
    }
    processedNode=startNode;
    startNode=startNode.getFirstChild();
    if (startNode == null) {
      startNode=processedNode.getNextSibling();
    }
    while (startNode == null) {
      processedNode=processedNode.getParentNode();
      if (processedNode == startParent) {
        return true;
      }
      startNode=processedNode.getNextSibling();
    }
  }
  return true;
}

public static boolean protectAgainstWrappingAttack ( Node startNode , String value ) { Node startParent = startNode . getParentNode ( ) ; Node processedNode = null ; Element foundElement = null ; String id = value . trim ( ) ; if ( ! id . isEmpty ( ) && id . charAt ( 0 ) == '#' ) { id = id . substring ( 1 ) ; } while ( startNode != null ) { if ( startNode . getNodeType ( ) == Node . ELEMENT_NODE ) { Element se = ( Element ) startNode ; NamedNodeMap attributes = se . getAttributes ( ) ; if ( attributes != null ) { for ( int i = 0 ; i < attributes . getLength ( ) ; i ++ ) { Attr attr = ( Attr ) attributes . item ( i ) ; if ( attr . isId ( ) && id . equals ( attr . getValue ( ) ) ) { if ( foundElement == null ) { foundElement = attr . getOwnerElement ( ) ; } else { log . log ( java . util . logging . Level . FINE , "Multiple elements with the same 'Id' attribute value!" ) ; return false ; } } } } } processedNode = startNode ; startNode = startNode . getFirstChild ( ) ; if ( startNode == null ) { startNode = processedNode . getNextSibling ( ) ; } while ( startNode == null ) { processedNode = processedNode . getParentNode ( ) ; if ( processedNode == startParent ) { return true ; } startNode = processedNode . getNextSibling ( ) ; } } return true ; }
this method is a tree - search to help prevent against wrapping attacks . it checks that no two elements have id attributes that match the " value " argument , if this is the case then " false " is returned . note that a return value of " true " does not necessarily mean that a matching element has been found , just that no wrapping attack has been detected .
