title: WebDriver Selenium API: identifying a WebElement in XPath
body: <p>I have recently started with Selenium, and I've decided to use only Selenium 2 / WebDriver.
  In my test code, I often arrive at a <a href="http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html" rel="nofollow noreferrer"><code>WebElement</code></a> without knowing where it is in the page.</p>
  
  <p>I'd like to have code that, given an WebElement, constructs an XPath expression to uniquely select it.</p>
  
  <p>FireFox recorder plugins for Selenium do this; what I want is code to do it in Selenium 2.</p>
  
  <p>I can write such code myself by using <code>WebElement</code>'s <code>findElement</code> to <a href="https://stackoverflow.com/questions/9021074/how-to-find-all-parent-elements-using-selenium-c-sharp-webdriver">walk up the tree</a> and <code>findElements</code> to find the child we came from, but it's nontrivial to come up with something fast (repeatedly calling <code>By.xpath</code> seems bad) and complete (e.g. due to namespaces).</p>
  
  <p>(<a href="https://stackoverflow.com/questions/7415960/selenium-webdriver-xpath-generation">A related question</a> suggests using CSS selectors instead - that's fine with me.)</p>
  
  <p>Has anyone done this for me?  What is the best approach?</p>