我如何在 XPATH 中获取特定标记?

How do I get a specific tag in XPATH?

我正在尝试获取 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. p 元素绑定到 XHTML 命名空间。您正在引用 "no namespace" 中名为 "p" 的元素。声明 XHTML 命名空间并在 XPath 中使用命名空间前缀。
  2. 谓词(方括号)的行为类似于 SQL where 子句,并且是方括号前面的项目的过滤器。您的原始 XPath 试图从 $data 中具有 p 子元素的任何元素中寻址所有 text() 节点,而不是从中选择所有 text() 节点所有 XHTML p 元素。

(: 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