Contoh XPath
Mari kita coba mempelajari beberapa sintaks dasar XPath dengan melihat beberapa contoh.
Dokumen Contoh XML
Kami akan menggunakan dokumen XML berikut dalam contoh di bawah ini.
"buku.xml":
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Lihat file "books.xml" di browser Anda .
Memuat Dokumen XML
Menggunakan objek XMLHttpRequest untuk memuat dokumen XML didukung di semua browser modern.
var xmlhttp = new XMLHttpRequest();
Kode untuk browser lama (IE5 dan IE6) dapat ditemukan di tutorial AJAX.
Memilih Node
Sayangnya, ada cara berbeda untuk menangani XPath di browser yang berbeda.
Chrome, Firefox, Edge, Opera, dan Safari menggunakan metode evaluasi() untuk memilih node:
xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null);
Internet Explorer menggunakan metode selectNodes() untuk memilih node:
xmlDoc.selectNodes(xpath);
Dalam contoh kami, kami telah menyertakan kode yang harus berfungsi dengan sebagian besar browser utama.
Pilih semua judul
Contoh berikut memilih semua node judul:
Contoh
/bookstore/book/title
Pilih judul buku pertama
Contoh berikut memilih judul node buku pertama di bawah elemen toko buku:
Contoh
/bookstore/book[1]/title
Pilih semua harga
Contoh berikut memilih teks dari semua node harga:
Contoh
/bookstore/book/price[text()]
Pilih node harga dengan harga>35
Contoh berikut memilih semua node harga dengan harga lebih tinggi dari 35:
Contoh
/bookstore/book[price>35]/price
Pilih node judul dengan harga>35
Contoh berikut memilih semua node judul dengan harga lebih tinggi dari 35:
Contoh
/bookstore/book[price>35]/title