How do I get a specific tag in XPATH?
I am trying to get the p tag but was not successful. Below is the data I am trying to get.
for $i in $data
let $ptag := $i//*[p]/text()
(: $data example :)
<div xmlns="http://www.w3.org/1999/xhtml">
<div class="title">my title</div>
<div class="course">
<div class="room">112</div>
<div class="teacher">Mr. Wilson</div>
<div class="student">123456</div>
<p>approved</p>
</div>
</div>
+3
source to share
1 answer
Two questions:
- The element is
p
bound to the XHTML namespace. You are referencing an element named "p" in "no namespace". Declare an XHTML namespace and use the namespace prefix in XPath. - The predicate (square brackets) behaves like an SQL where clause and is a filter for the item preceding the square brackets. Your original XPath tried to address all nodes
text()
from any element in$data
that has a childp
, instead of selecting all nodestext()
from all xHTML p elements.
(: declare a namespace prefix for the XHTML namespace,
in order to use in the XPath below :)
declare namespace x="http://www.w3.org/1999/xhtml";
(: $data example :)
let $data :=
<div xmlns="http://www.w3.org/1999/xhtml">
<div class="title">my title</div>
<div class="course">
<div class="room">112</div>
<div class="teacher">Mr. Wilson</div>
<div class="student">123456</div>
<p>approved</p>
</div>
</div>
return
for $i in $data
(: use the namespace prefix "x" when addressing the HTML p element
and pull it out of the predicate
:)
let $ptag := $i//x:p/text()
return $ptag
+6
source to share