XPath Examples
- Previous Page XPath Operators
- Next Page XPath Summary
في هذا الفصل، دعونا نتعلم بعض الجمل الأساسية لـ XPath عبر الأمثلة.
مثال XML
نحن سنستخدم هذا الملف XML في المثال التالي:
"books.xml" :
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book category="COOKING"> <title lang="en">ايطالياى روزانه</title> <author>جيادا دى لورنتيس</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">هاری پاتر</title> <author>جى كى. رولينگ</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>
تحميل مستند XML
جميع المتصفحات الحديثة تدعم استخدام XMLHttpRequest لتحميل مستندات XML.
كود لمعظم المتصفحات الحديثة:
var xmlhttp=new XMLHttpRequest();
كود لتحديد المتصفحات القديمة من Microsoft (IE 5 و 6):
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
اختيار العناصر
للأسف، Internet Explorer وغيره يتعامل مع XPath بطريقة مختلفة.
في مثالنا، يحتوى الكود على دعم لأغلب المتصفحات الشائعة.
يستخدم Internet Explorer طريقة selectNodes() لاختيار العناصر من مستند XML:
xmlDoc.selectNodes(xpath);
يستخدم Firefox و Chrome و Opera و Safari طريقة evaluate() لاختيار العناصر من مستند XML:
xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null);
اختيار جميع العناصر بعنوان
السعيلى امثلة هلى اختيار جميع عناصر التى تحتوى على عنوان
/bookstore/book/title
Select the title of the first book
The following example selects the title of the first book node under the bookstore element:
/bookstore/book[1]/title
There is a problem here. The above example outputs different results in IE and other browsers.
IE5 and higher versions treat [0] as the first node, while according to W3C standards, it should be [1].
To solve the [0] and [1] issues in IE5+, you can set the language selection (SelectionLanguage) for XPath.
The following example selects the title of the first book node under the bookstore element:
xml.setProperty("SelectionLanguage","XPath"); xml.selectNodes("/bookstore/book[1]/title");
Select all prices
The following example selects all text in the price node:
/bookstore/book/price/text()
Select price nodes with a price greater than 35
The following example selects all price nodes with a price greater than 35:
/bookstore/book[price>35]/price
Select title nodes with a price greater than 35
The following example selects all title nodes with a price greater than 35:
/bookstore/book[price>35]/title
- Previous Page XPath Operators
- Next Page XPath Summary