谢谢大家。经过几乎一整天的思考和编程,我决定必须使用原生 htmlElement 而不是 htmlagilitypack HtmlNode,因为我想在 webbrowser 中将文本输入到 Htmlelement 中。所以这是我想出的代码。如果有人用 htmlagilitypack 展示解决方案,我仍然会很感激。
public HtmlElement selectHtmlNode(string xPath, HtmlElement htmlElement)
{
string currentNode;
int indexOfElement;
//get string representation of current Tag.
if (xPath.Substring(1,xPath.Length-2).Contains('/'))
currentNode = xPath.Substring(1, xPath.IndexOf('/', 1) - 1);
else
currentNode = xPath.Substring(1, xPath.Length-1);
//gets the depth of current xPath
int numOfOccurence = Regex.Matches(xPath, "/").Count;
//gets the children's index
int.TryParse(Regex.Match(currentNode, @"\d+").Value, out indexOfElement);
//if i have to select nth-child ex: /tr[4]
if (indexOfElement > 1)
{
currentNode = currentNode.Substring(0, xPath.IndexOf('[') - 1);
//the tag that i want to get
if (numOfOccurence == 1 || numOfOccurence == 0)
{
return htmlElement.Children[indexOfElement - 1];
}
//still has some children tags
if (numOfOccurence > 1)
{
int i = 1;
//select nth-child
foreach (HtmlElement tempElement in htmlElement.Children)
{
if (tempElement.TagName.ToLower() == currentNode && i == indexOfElement)
{
return selectHtmlNode(xPath.Substring(xPath.IndexOf('/', 1)), tempElement);
}
else if (tempElement.TagName.ToLower() == currentNode && i < indexOfElement)
{
i++;
}
}
}
}
else
{
if (numOfOccurence == 1 || numOfOccurence == 0)
{
return htmlElement.FirstChild;
}
if (numOfOccurence > 1)
{
foreach (HtmlElement tempElement in htmlElement.Children)
{
if (tempElement.TagName.ToLower() == currentNode)
{
return selectHtmlNode(xPath.Substring(xPath.IndexOf('/', 1)), tempElement);
}
}
}
}
return null;
}
函数就是这样调用的。其中 htmlController 是某个类的实例。
HtmlElement currentElement = htmlController.selectHtmlNode("/body/form/div/div[2]/div/div/input", webBrowser.Document.GetElementsByTagName("html")[0]);
currentElement.SetAttribute("Value", "hello world");