title: Is there a better way to generate HTML from an XPATH string?
body: <p>We want to write JUnit tests for complex java code that uses Selenium webDriver on very complex web pages.  </p>
  
  <p>We found that saving the web pages always alters the xpaths, so that's out. Mocking the WebDriver, WebElements etc. was difficult and messy.</p>
  
  <p>In the end, we've chosen to generate the HTML files for the XPATHS used by the logic, then have the webDriver simply load the test HTML pages.</p>
  
  <p>We wrote the code below and it works <em>most</em> of the time.  But before we develop it further, we're asking if there's a simpler/better way or a library or utility for this purpose.</p>
  
  <pre class="lang-java prettyprint-override"><code>   public void generateHtml(String xPath) {
  
          ArrayList&lt;String&gt; htmlDoc = new ArrayList&lt;&gt;();
          htmlDoc.add("&lt;!DOCTYPE html&gt;");
  
          Pattern patt = Pattern.compile("\\[(\\d+)]");
          Matcher matcher;
  
          String[] tokens = xPath.substring(1).split("/");
          ArrayList&lt;String&gt; closeTags = new ArrayList&lt;&gt;();
  
          for (final String token : tokens) {
              final String tag = token.split("\\[")[0];
  
              // collect closing tags
              closeTags.add(mkCloseTag(tag));
  
              // get the index if present
              matcher = patt.matcher(token);
              int idx = 0;
              if (matcher.find()) {
                  idx = Integer.parseInt(matcher.group(1));
              }
  
              // if indexed, create enough empty tag pairs up to the indexed one
              if (idx &gt; 0) {
                  for (int i = 1; i &lt; idx; ++i) {
                      htmlDoc.add(mkTag(tag) + idx);
                      htmlDoc.add(mkCloseTag(tag));
                  }
              }
  
              // append an extra tag pair if idx is 1
              if (idx == 1) {
                  closeTags.add(mkTag(tag) + idx);
                  closeTags.add(mkCloseTag(tag));
              }
  
              htmlDoc.add(mkTag(tag));
          }
  
          // append all the close-tags
          Collections.reverse(closeTags);
          htmlDoc.addAll(closeTags);
  
          for(String t : htmlDoc) {
              System.out.println(t);
          }
      }
  </code></pre>
  
  <p>Example of an xpath we're dealing with:</p>
  
  <pre><code>/html/body/div[6]/div[3]/div/div[2]/div/div[2]/div/div[2]/div/form/table/tbody/tr/td/table/tbody/tr[2]/td[2]/div/div[2]/div/table/tbody/tr/td/input
  </code></pre>