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 📝:
<parent>
<child></child>
</parent><parent>
<child></child>
<grandchild></grandchild>
</parent><parent>
<child></child>
</parent><root>
<parent>
<child></child>
</parent>
</root><element attribute="value"/>Now that we've covered the basics, let's move on to XPath relationships 💡:
/ symbol followed by the child's element name./parent/child[@] symbol followed by the attribute name./parent/child[@attribute]/parent/child/grandchild/parent/../parent/.. /parent/..Let's put our knowledge to the test with a quiz 📝:
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.
<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:
/library/book[1]/titleAnd the ID of the author of the second book:
/library/book[2]/author/@idThat's it for today! We hope you enjoyed learning about XPath relationships. Stay tuned for more lessons on CodeYourCraft! 🎯