Trục XPath
Tài liệu Ví dụ về XML
Chúng tôi sẽ sử dụng tài liệu XML sau trong các ví dụ dưới đây.
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
Trục XPath
Một trục thể hiện mối quan hệ với nút ngữ cảnh (hiện tại) và được sử dụng để định vị các nút liên quan đến nút đó trên cây.
AxisName | Result |
---|---|
ancestor | Selects all ancestors (parent, grandparent, etc.) of the current node |
ancestor-or-self | Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself |
attribute | Selects all attributes of the current node |
child | Selects all children of the current node |
descendant | Selects all descendants (children, grandchildren, etc.) of the current node |
descendant-or-self | Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself |
following | Selects everything in the document after the closing tag of the current node |
following-sibling | Selects all siblings after the current node |
namespace | Selects all namespace nodes of the current node |
parent | Selects the parent of the current node |
preceding | Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes |
preceding-sibling | Selects all siblings before the current node |
self | Selects the current node |
Biểu thức Đường dẫn Vị trí
Đường dẫn vị trí có thể là tuyệt đối hoặc tương đối.
Đường dẫn vị trí tuyệt đối bắt đầu bằng dấu gạch chéo (/) và đường dẫn vị trí tương đối thì không. Trong cả hai trường hợp, đường dẫn vị trí bao gồm một hoặc nhiều bước, mỗi bước được phân tách bằng dấu gạch chéo:
An absolute location path:
/step/step/...
A relative location path:
step/step/...
Mỗi bước được đánh giá dựa trên các nút trong tập hợp nút hiện tại.
Một bước bao gồm:
- một trục (xác định mối quan hệ cây giữa các nút đã chọn và nút hiện tại)
- kiểm tra nút (xác định một nút trong một trục)
- không hoặc nhiều vị từ (để tinh chỉnh thêm tập hợp nút đã chọn)
Cú pháp cho bước vị trí là:
axisname::nodetest[predicate]
Các ví dụ
Example | Result |
---|---|
child::book | Selects all book nodes that are children of the current node |
attribute::lang | Selects the lang attribute of the current node |
child::* | Selects all element children of the current node |
attribute::* | Selects all attributes of the current node |
child::text() | Selects all text node children of the current node |
child::node() | Selects all children of the current node |
descendant::book | Selects all book descendants of the current node |
ancestor::book | Selects all book ancestors of the current node |
ancestor-or-self::book | Selects all book ancestors of the current node - and the current as well if it is a book node |
child::*/child::price | Selects all price grandchildren of the current node |