如何在XPATH中获取特定标签?

时间:2017-06-13 19:34:26

标签: xpath marklogic

我正在尝试获取p标签,但尚未成功。以下是我想要获得的数据。

  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>

1 个答案:

答案 0 :(得分:6)

两个问题:

  1. p元素绑定到XHTML名称空间。您正在“无名称空间”中引用名为“p”的元素。声明XHTML命名空间并在XPath中使用namespace-prefix。
  2. 谓词(方括号)的行为类似于SQL where子句,并且是方括号前面的项目的filteres。您的原始XPath尝试从text()中具有$data子元素的任何元素处理所有p个节点,而不是从中选择所有text()个节点所有的XHTML p元素。
  3. (: 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