如何根据当前节点属性返回其他节点


How to return additional node depending on current node attribute

我们有这样的结构:

<class>
  <class-intro>
    <indication>Some content</indication>
  </class-intro>
  <article>
    <indication>Special content</indication>
  </article>
  <article includeclass="no">
    <indication>Different content</indication>
  </article>
</class>

我正在尝试在每篇文章的基础上使用 XQuery/XPath 选择这些:

indication | node()[not(@includeclass) | @includeclass='yes']/ancestor::class/class-intro/indication

注意 - 我正在使用PHP的 http://php.net/manual/en/class.domxpath.php

// $xpath is a DOMXPath for the above document
$articles = $xpath->query("//article");
$indications = array();
foreach ($articles as $article) {
  $indications[] = $xpath->query(
    "indication | node()[not(@includeclass) | @includeclass='yes']/ancestor::class/class-intro/indication",
    $article
  );
}
var_dump($indications);

我期待得到:

array(
  0 => array(
    0 => "Some content",
    1 => "Special content",
  ),
  1 => array(
    0 => "Different content",
  ),
);

但我得到:

array(
  0 => array(
    0 => "Some content",
    1 => "Special content",
  ),
  1 => array(
    0 => "Some content",
    1 => "Different content",
  ),
);

问题是因为在这种情况下not(@includeclass)总是对每个node()进行true计算,因为article的子元素都没有属性includeclass

你应该使用self轴来引用当前上下文节点,即使用self::node()而不是node(),因为includeclass属性属于当前上下文元素article,而不是子节点:

self::node()[not(@includeclass) or @includeclass='yes']/ancestor::class/.....