He creado un selector de HTMLElement (DOM) utilizando el .net WebBrowser predeterminado. El usuario puede seleccionar (seleccionar) un HTMLElement haciendo clic en él.
Quiero obtener el HtmlAgilityPack.HTMLNode correspondiente al HTMLElement.
La forma más fácil (en mi opinión) es usar doc.DocumentNode.SelectSingleNode (EXACTHTMLTEXT) pero no funciona realmente (porque la función solo acepta el código xpath).
¿Cómo puedo hacer esto?
Una muestra de HTMLElement seleccionada por un usuario se parece a esto (el Código OuterHtml):
<a onmousedown="return wow" class="l" href="http://site.com"><em>Great!!!</em> <b>come and see more</b></a>
Por supuesto, se puede seleccionar cualquier elemento, por eso necesito una forma de obtener el HTMLNode.
El mismo concepto, pero un poco más sencillo porque no tiene que conocer el tipo de elemento:
HtmlNode n = doc.DocumentNode.Descendants().Where(n => n.OuterHtml.Equals(text, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
Se me ocurrió una solución. No sé si es lo mejor (agradecería que alguien conozca una mejor manera de hacerlo para que me avise).
Aquí está la clase que obtendrá el HTMLNode:
public HtmlNode GetNode(string text)
{
if (text.StartsWith("<")) //get the type of the element (a, p, div etc..)
{
string type = "";
for (int i = 1; i < text.Length; i++)
{
if (text[i] == ' ')
{
type = text.Substring(1, i - 1);
break;
}
}
try //check to see if there are any nodes of your HTMLElement type that have an OuterHtml equal to the HtmlElement Outer HTML. If a node exist, than that's the node we want to use
{
HtmlNode n = doc.DocumentNode.SelectNodes("//" + type).Where(x => x.OuterHtml == text).First();
return n;
}
catch (Exception)
{
throw new Exception("Cannot find the HTML element in the HTML Page");
}
}
else
{
throw new Exception("Invalid HTML Element supplied. The selected HTML element must start with <");
}
}
La idea es que pases el OuterHtml de HtmlElement. Ejemplo:
HtmlElement el=....
HtmlNode N = GetNode(el.OuterHtml);