This is a collection of XPath examples (raw XPath and java methods using HtmlUnit's XPath functionality) that have proven useful.

/**
* This is a method I use that will allow you to search for elements using tag name, attribute, and value and allows
* a wildcard "*" for any of these.
*/
    
public List getValuesByAttributes(final Object uniquePageObject, final String tagName,
            
final String attribute, final String value) {
        
final List retVal = new ArrayList();
        
final HtmlPage pg = getHtmlPageForObject(uniquePageObject);
        
String exp = "//" + tagName;
        if (
"*".equalsIgnoreCase(value)) {
            
exp += "[@" + attribute + "]";
        } else {
            
exp += "[@" + attribute + "='" + value + "']";
        }
        List
foundNodes;
        
try {
            
final HtmlUnitXPath xpath = new HtmlUnitXPath(exp);
            
foundNodes = xpath.selectNodes(pg);
        }
catch (JaxenException e) {
            return new
ArrayList();
        }

        
final Iterator i = foundNodes.iterator();

        while (
i.hasNext()) {
            
final String thisOne = ((HtmlElement) i.next()).asText();
            
retVal.add(thisOne);
        }

        return
retVal;
    }

/**
* Our testing framework is based on the concept of "widgets" that are just a holder of either an ID
* or an XPath expression that will identify the element on the page. This is the method we use
* to find the element from the widget inside the framework.
*/

    
private HtmlElement getElementFromWidget(final HtmlPage htmlPage, final Widget widget) {
        
final String widgetContents = widget.toString();
        
final HtmlElement element;
        if (
widgetContents.startsWith("/")) {
            
try {
                
final HtmlUnitXPath xpath = new HtmlUnitXPath(widgetContents);
                
element = (HtmlElement) xpath.selectSingleNode(htmlPage);
            }
catch (final JaxenException e) {
                
throw new WebAdapterException("Element does not exist!", e);
            }
            if (
element == null) {
                
throw new WebAdapterException("Element does not exist!");
            }
        } else {
            
try {
                
element = htmlPage.getHtmlElementById(widgetContents);
            }
catch (final ElementNotFoundException e) {
                
throw new WebAdapterException("Element does not exist!", e);
            }
        }

        return
element;
    }