Search code examples
htmlxmlxpathhtml-agility-pack

Selecting element based on attribute order in XPath?


I am working on a project using the Html-Agility-Pack and I need to build a list of each link that has an href attribute as its first attribute. What XPath expression would be used for this?

Example (I would want to only select the first):

  1. <a href="http://someurl.com"/>
  2. <a id="someid" href="http://someurl.com"/>

Solution

  • No, don't do that.

    You really don't want to select elements based upon the ordering of their attributes because attribute order is arbitrary in HTML and XML. Find another criteria to limit your selections:

    • attribute presence or attribute value
    • child element presence or string value
    • preceding element value, possibly a label
    • etc

    You want to choose a criteria that's invariant across all instances of the HTML/XML documents you may encounter. Attribute order is not such a criteria.