title: XPath with optional element in hierarchy
body: <p>As in this <a href="https://stackoverflow.com/questions/4608097/xpath-to-select-a-table-row-that-has-a-cell-containing-specified-text/4608452#4608452">Stack Overflow answer</a> imagine that you need to select a particular table and then all the rows of it. Due to the permissiveness of HTML, all three of the following are legal markup:</p>
  
  <pre><code>&lt;table id="foo"&gt;&lt;tr&gt;...&lt;/tr&gt;&lt;/table&gt;
  &lt;table id="foo"&gt;&lt;tbody&gt;&lt;tr&gt;...&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
  &lt;table id="foo"&gt;&lt;tr&gt;...&lt;/tr&gt;&lt;tbody&gt;&lt;tr&gt;...&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
  </code></pre>
  
  <p>You are worried about tables nested in tables, and so don't want to use an XPath like<br>
  <code>table[@id="foo"]//tr</code>.</p>
  
  <p>If you could specify your desired XPath as a regex, it might look something like:<br>
  <code>table[@id="foo"](/tbody)?/tr</code></p>
  
  <p>In general, how can you specify an XPath expression that allows an optional element in the  hierarchy of a selector?</p>
  
  <p><em>To be clear, I'm not trying to solve a real-world problem or select a specific element of a specific document. I'm asking for techniques to solve a class of problems.</em></p>