Xpath
The question "How do you use XPath to find elements and attributes in an XML document?" will be answered in this section.
XPath is basically used to find elements and attributes in an XML document. The syntax and commands used in XPath are similar to the syntax and commands that are used in a computer filing systems. Below is the command list for XPath.
| name of the element/attribute | selects all child elements/attributes of the given element/attribute |
| / | selects from the root element/attribute |
| // | selects elements/attributes in the document from the current element/attribute that match the selection no matter where they are |
| . | selects the current element/attribute |
| .. | selects the parent of the current element/attribute |
| @ | selects attributes |
Using the XPath commands are straightforward. For example, in the code below, the path "classcard/subject" will take you to the subject tag of the XML file.
<?xml version = "1.0"?> <classcard dategiven = "9/27/05" xmlns:xlink = "http://www.w3.org/1999/xlink" > <name> Sara </name> <subject> programming </subject> <result> <grade> 3.5/4.0 </grade> very industrious and recites a lot </result> <complaints xlink:href = "http://www.mcdonalds.com"> Eats McDonald’s in the middle of class </complaints> </classcard>
If you are familiar with MS-DOS or Windows Explorer then you should not have any problems using XPath commands. Think of XPath like paths to your files on your own personal computer. See the image below and try to see the similarity.