Understanding the Difference Between .// and //* in XPath

Understanding the Difference Between .// and //* in XPath

21 May 2024 Stephan Petzl Leave a comment Tech-Help

When working with XPath, you might encounter expressions like .//*[@id='Passwd'] and //input[@type='password']. Understanding the difference between these expressions is crucial for accurate element selection in web scraping, automated testing, and other tasks involving XML and HTML documents.

Absolute vs Relative XPaths

XPath expressions can be either absolute or relative:

  • / introduces an absolute location path, starting at the root of the document.
  • . introduces a relative location path, starting at the context node.

Named Element vs Any Element

XPath allows for selecting specific named elements or any element:

  • /ename selects an ename root element.
  • ./ename selects all ename child elements of the context node.
  • /* selects the root element, regardless of name.
  • ./* or * selects all child elements of the context node, regardless of name.

Descendant-or-Self Axis

The descendant-or-self axis is another important concept in XPath:

  • //ename selects all ename elements in a document.
  • .//ename selects all ename elements at or beneath the context node.
  • //* selects all elements in a document, regardless of name.
  • .//* selects all elements, regardless of name, at or beneath the context node.

Practical Examples

To illustrate these concepts, let’s consider the following XPath expressions:

  • .//*[@id='Passwd'] means to select all elements at or beneath the context node that have an id attribute value equal to ‘Passwd’.
  • //input[@type='password'] means to select all input elements in the document that have a type attribute value equal to ‘password’.

Choosing the Right XPath Expression

When selecting the appropriate XPath expression, consider the following:

  • If you want to start the search from the root of the document, use an absolute path (e.g., //input[@type='password']).
  • If you want to start the search from a specific context node, use a relative path (e.g., .//*[@id='Passwd']).
  • Use * when the element name is not known but a specific attribute is known (e.g., //*[@id='Passwd']).

Enhancing Your Testing with Repeato

XPath expressions are essential for automated testing of web elements. If you’re looking for a comprehensive and intuitive tool to automate your app testing, consider Repeato. Repeato is a no-code test automation tool for iOS and Android that helps you create, run, and maintain automated tests for your apps. With its computer vision and AI capabilities, Repeato makes it particularly fast to edit and run tests, ensuring thorough coverage and reliability. Additionally, Repeato’s scripting interface allows advanced testers to automate complex use cases, making it an ideal solution for both beginners and experts.

Like this article? there’s more where that came from!