title: How to get the XPath of an element in HTML in java?
body: <p>I want to achieve a simple task, but I'm struggling to find an easy solution for that: i have the HTML of a webpage in a String (or File) and I'd like to generate the XPath of a given element.
  (For example i'd like to retrieve the XPath for an <code>&lt;a&gt;</code> element) </p>
  
  <p>I tried different solutions but I'm constantly encountering problems in parsing the html correctly. Is there a functioning html cleaner for java like this one?
  <a href="https://www.htmlwasher.com/" rel="nofollow noreferrer">https://www.htmlwasher.com/</a>
  This is the ONLY functioning cleaner i've find out for now, but it is an online tool. With this i can easely parse the HTML and get to the XPath.</p>
  
  <p>I'm currently using jOOX (<a href="https://github.com/jOOQ/jOOX" rel="nofollow noreferrer">https://github.com/jOOQ/jOOX</a>) this way to generate the XPath:</p>
  
  <pre><code>Document document = $(html).document();
  System.out.println($(document).find("a").xpath());
  </code></pre>
  
  <p>If the HTML is cleaned with the online tool i provided, i can generate the right XPath.
  I like the way i could interact with jOOX if only i could correctly and programmatically parse the html. Do you know a good way to parse the HTML?
  I already tried:</p>
  
  <ul>
  <li>JSoup </li>
  <li>Tagsoup</li>
  <li>HtmlCleaner</li>
  </ul>
  
  <p>The testing website page is <a href="http://www.ansa.it" rel="nofollow noreferrer">http://www.ansa.it</a>.</p>
  
  <p><strong>EDIT</strong>:
  The parsing was failing on some common HTML parsing problems like unclosed tags ( <code>&lt;/img&gt;</code> for example), escaping, etc.</p>
  
  <p>I managed to parse "correctly" the html this way:</p>
  
  <p><code>Document doc = Jsoup.parse(Jsoup.clean(html, Whitelist.relaxed()));
  doc.outputSettings().escapeMode(EscapeMode.xhtml)
                          .syntax(Syntax.xml)
                          .charset(StandardCharsets.UTF_8);</code></p>
  
  <p>Fact is that tags like <code>&lt;a href="cinema.shtml"&gt;Cinema&lt;/a&gt;</code> became <code>&lt;a&gt;Cinema&lt;/a&gt;</code> so i'm not able to select them using their attributes, like href. How can i solve this new problem?</p>
  
  <p>I noticed that some links still have their href and they are the ones wich point to other websites like facebook or twitter. Could this be related?</p>