Search code examples
xpathmarklogic

How do I get a specific tag in XPATH?


I'm trying to get the p tag, but have not been successful. The below is the data that I'm 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>

Solution

  • Two issues:

    1. The p element is bound to the XHTML namespace. You are referencing an element named "p" in the "no namespace". Declare the XHTML namespace and use the namespace-prefix in your XPath.
    2. The predicate (square braces) behave like a SQL where clause and are filteres for the item preceding the square braces. Your original XPath was attempting to address all of the text() nodes from any element in the $data that have a p child element, rather than selecting all of the text() nodes from all of the 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