XPath Relationships 🎯

beginner
17 min

XPath Relationships 🎯

Welcome back to CodeYourCraft! Today, we're diving into XPath Relationships. If you're new here, XPath is a language used to navigate and extract data from XML documents.

Let's start with the basics 📝:

  • Child: A child is an element that is directly under another element (parent).
xml
<parent> <child></child> </parent>
  • Descendant: A descendant is any element that is below another element, no matter how many levels deep.
xml
<parent> <child></child> <grandchild></grandchild> </parent>
  • Parent: The parent is the element that contains another element.
xml
<parent> <child></child> </parent>
  • Ancestor: An ancestor is any element that contains another element, including the root element.
xml
<root> <parent> <child></child> </parent> </root>
  • Attribute: An attribute is a named value that describes an element in an XML document.
xml
<element attribute="value"/>

Now that we've covered the basics, let's move on to XPath relationships 💡:

  • Child Selection: To select a child, you use the / symbol followed by the child's element name.
bash
/parent/child
  • Attribute Selection: To select an attribute, you use the [@] symbol followed by the attribute name.
bash
/parent/child[@attribute]
  • Descendant Selection: To select a descendant, you use a combination of child and descendant selectors.
bash
/parent/child/grandchild
  • Parent Selection: To select a parent, you use a parent selector followed by the child selector.
bash
/parent/..
  • Ancestor Selection: To select an ancestor, you use a combination of parent and ancestor selectors.
bash
/parent/.. /parent/..

Let's put our knowledge to the test with a quiz 📝:

Quick Quiz
Question 1 of 1

What is the XPath to select the first `grandchild` in the following XML?

Let's wrap up with a practical example 💡:

Suppose we have an XML representing a library catalog with books and their authors.

xml
<library> <book id="1"> <title>Book 1</title> <author id="1">Author 1</author> </book> <book id="2"> <title>Book 2</title> <author id="2">Author 2</author> </book> </library>

Using XPath relationships, we can extract the title of the first book:

bash
/library/book[1]/title

And the ID of the author of the second book:

bash
/library/book[2]/author/@id

That's it for today! We hope you enjoyed learning about XPath relationships. Stay tuned for more lessons on CodeYourCraft! 🎯