Select single and multiple options

For similar example using Selenium v1, see Select single/multiple options.

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
 
/**
 * Selenium v2: Select single and multiple options.
 * It is assumed that Firefox is installed on your computer.
 * @Author: Xuan Ngo
 */ 
public class SelectExample2
{
  public static void main(String[] args)
  {
    // Run all actions on Firefox.
    WebDriver oWebDriver = new FirefoxDriver();
 
    // Open the webpage.
    oWebDriver.get("http://openwritings.net/sites/default/files/select.html");
 
    /**
     *  Single Selection: Select July.
     */
    // Find <select> element of "Single selection" using ID locator.
    Select oSingleSelection = new Select(oWebDriver.findElement(By.id("single-selection")));
 
    // Select <option ...>July</option>
    oSingleSelection.selectByVisibleText("July");
 
    /**
     * Multiple Selections: Use variations of locators to select February, August and November.
     */
    // Find <select> element of "Multiple selection" using XPATH locator.
    Select oMulitpleSelection = new Select(oWebDriver.findElement(By.xpath("//select[@multiple='multiple' and @size=12]")));
 
    // Clear all selected entries.
    oMulitpleSelection.deselectAll();
 
    // Select February, August and November using different functions.
    oMulitpleSelection.selectByIndex(1); // February
    oMulitpleSelection.selectByValue("Aug"); // Select <option ... value="Aug">...</option>
    oMulitpleSelection.selectByVisibleText("November"); // Select <option ...>November</option>
 
    /**
     * Pause so that you can see the results.
     */
    pause(10000); 
 
    /**
     * Close the browser.
     */
    oWebDriver.close(); 
  }
 
  /**
   * Pause for X milliseconds.
   * @param iTimeInMillis
   */
  public static void pause(final int iTimeInMillis)
  {
    try
    {
      Thread.sleep(iTimeInMillis);
    }
    catch(InterruptedException ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
}