web analytics

Learning XPath Expressions By Examples

Options

codeling 1595 - 6639
@2016-01-15 20:45:03

XPath is a language for finding information in an XML document. XPath uses path expressions to navigate through elements and attributes in an XML document. The postings in this topic illustrate how to form all kinds of Xpath expressions to navigate an XML document describing a book.

Book.xml

The following XML document is used to describe a book:

  • Book has its title,ISBN,price, author, publish date and publisher.
  • Book contains a lot of chapters
  • Each chapter has its chapter number, title and at least one paragraph.
<?xml version="1.0"?>
<!-- This XML docuemnt is used to define a book -->
<book isbn="5CC60E5B-A25C-4aeb-B158-3998EE660FCD">
    <title>XSLT</title>
    <author>James Renaud</author>
    <publishDate>2007/11/10</publishDate>
    <publisher>ABC Book Company</publisher>
    <price currency="USD">28.88</price>
    <!-- Chapter 1 -->
    <chapter id="1">
        <title>Getting Started</title>
        <!-- Paragraph 1 in chapter 1 -->
        <para>1.1 para.</para>
        <summary>summary for chapter 1</summary>
    </chapter>
    <chapter id="2">
        <title>The Hello World Example</title>
        <para>2.1 para.</para>
        <para>2.2 para.</para>
        <para>2.3 para.</para>
    </chapter>
    <chapter id="3">
        <title>XPath</title>
        <para>3.1 para</para>
    </chapter>
    <chapter id="4">
        <title>Stylesheet Basics</title>
        <para>4.1 para.</para>
        <para>4.2 para.</para>
        <para>4.3 para.</para>
        <para>4.4 para.</para>
    </chapter>
    <chapter id="5">
        <title>Branching and Control Elements</title>
        <para>5.1 para.</para>
    </chapter>
    <chapter id="6">
        <title>Functions</title>
        <para>6.1 para.</para>
        <summary>summary for chapter 6</summary>
    </chapter>
    <chapter id="7">
        <title>Creating Links and Cross-References</title>
        <para>7.1 para.</para>
        <para>7.2 para.</para>
    </chapter>
    <chapter id="8">
        <title>Sorting and Grouping Elements</title>
        <para>8.1 para.</para>
    </chapter>
    <chapter id="9">
        <title>Combining XML Documents</title>
        <para>9.1 para.</para>
        <summary>summary for chapter 9</summary>
    </chapter>
</book>

The following XPath expressions demonstrate you how to use XPath to locate the information in the above Book.xml. All the results shown below are parsed by Altova XMLSpy.

@2016-01-15 20:47:03

How many chapters does this book have?

count(//chapter)
count(/book/chapter)

 

@2016-01-15 20:48:59

Select all chapters

//chapter
/book/chapter
/book/child::chapter
//chapter/self::*

 

@2016-01-15 20:51:32

Who wrote this book?

/book/author

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com