How to edit and run XPath expressions
XPath is a language for finding information in an XML Document. XPath models an XML Document as a tree of nodes. XPath expressions look very much like the expressions you see when you work with a traditional computer file system, for example:
|
Select all "chapters" within "book". |
/book/chapter[@title="Anomaly"] |
Select all "chapters" within "book" with attribute title "Anomaly". |
|
Select all "chapters" anywhere in the document. |
//chapter[2] |
Select the second "chapter" anywhere in the document. |
//comment() |
Select all comment in the document. |
XPath and Namespaces
To select nodes in a namespace, a prefix must be used to indicate the namespace. For example, the following XML contains three namespaces:
<pets:pets
xmlns="https://www.xmlblueprint.com/guinea-pigs"
xmlns:cats="https://www.xmlblueprint.com/cats"
xmlns:dogs="https://www.xmlblueprint.com/dogs"
xmlns:pets="https://www.xmlblueprint.com/pets">
<cats:cat breed="British Shorthair"/>
<cats:cat breed="Burmese"/>
<dogs:dog breed="Cocker Spaniel"/>
<cats:cat breed="Egyptian Mau"/>
<dogs:dog breed="Golden Retriever"/>
<guinea-pig breed="Harlequin"/>
<guinea-pig breed="Himalayan"/>
<cats:cat breed="Siamese"/>
<guinea-pig breed="Somali"/>
</pets:pets>
prefix |
namespace |
cats |
{https://www.xmlblueprint.com/cats} |
dogs |
{https://www.xmlblueprint.com/dogs} |
no prefix |
{https://www.xmlblueprint.com/guinea-pigs} |
To select nodes in namespace {https://www.xmlblueprint.com/cats}, prefix "cats" must be used. For instance, the XPath expression //cats:cat selects all cats in namespace {https://www.xmlblueprint.com/cats}:
<cats:cat breed="British Shorthair"/>
<cats:cat breed="Burmese"/>
<cats:cat breed="Egyptian Mau"/>
<cats:cat breed="Siamese"/>
To select nodes in namespace {https://www.xmlblueprint.com/dogs}, prefix "dogs" must be used. For instance, the XPath expression //dogs:dog selects all dogs in namespace {https://www.xmlblueprint.com/dogs}:
<dogs:dog breed="Cocker Spaniel"/>
<dogs:dog breed="Golden Retriever"/>
Using XPath in XMLBlueprint
To use XPath in XMLBlueprint, open the XPath view (View > XPath).
|
• | Open the XML Document you want to query. |
• | Type an XPath expression (e.g. //xsl:template) in the edit box and press enter. |
• | The results of the XPath query are returned below the edit box. |
• | Click on a node to select the node in the active editor. |
Default Namespace
XPath 1.0 - Use prefix "default" to indicate the default namespace. For instance, to select all guinea-pigs in the default namespace {https://www.xmlblueprint.com/guinea-pigs}, use //default:guinea-pig.
XPath 2.0 and up - Use prefix "default" to indicate the default namespace or use no prefix at all. For instance, to select all guinea-pigs in the default namespace {https://www.xmlblueprint.com/guinea-pigs}, use //default:guinea-pig or //guinea-pig.