rrrr-o
rrrr-o

Reputation: 2516

How do I find attributes starting with a specific value using HTML Agility Pack?

I am trying to find any attributes within an HTML document that start with a particular value. I seem to have a valid XPath query for this but it returns nothing when using HTML Agility Pack.

I'm aware I could be using Linq but I'm attempting to reuse existing functionality and leverage an XPath query.

Example HTML

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>Loren ipsum</p>
<a href="http://www.myurl.com" onclick="myFunction()"></a>
</body>
</html>

XPath query

//*/@*[starts-with(name(), 'on')]

Is this possible using HTML Agility Pack?

Upvotes: 1

Views: 820

Answers (2)

har07
har07

Reputation: 89285

Using HtmlAgilityPack (HAP) and XPath function name() didn't work for me, but replacing name() with local-name() did the trick :

//*/@*[starts-with(local-name(), 'on')]

However, both SelectSingleNode() and SelectNodes() only able to return HtmlNode(s). When the XPath expression selects an attribute instead of node, the attribute's owner node would be returned. So in the end you still need to get the attribute through some options besides XPath, for example :

HtmlDocument doc;
......
var link = doc.DocumentNode
              .SelectSingleNode("//*/@*[starts-with(local-name(), 'on')]");
var onclick = link.Attributes
                  .First(o => o.Name.StartsWith("on"));

Upvotes: 2

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 22617

Your XPath expression is correct. Taking as input the document snippet you have shown, the result is

onclick="myFunction()"

So, yes this is definitely possible and XPath is not at fault here, the problem lies somewhere else. Perhaps you could show the code that invokes the expression? Do you use SelectSingleNode()?

Upvotes: 0

Related Questions