dtufl26404 2015-11-02 03:53
浏览 46

如果项目具有一个或多个子元素,则xpath不匹配

I have a method that looks like this:

function braces(DOMElement $node){
    $path   = $node->getNodePath();
    $xpath = new DOMXPath($node->ownerDocument);
    $nodes = $xpath->query($path . '[*=(contains(., "{{") and contains(., "}}"))]');

    var_dump($nodes);
}

I have created the following two test cases:

Test Case 1

$dom = new DOMDocument();
$dom->loadHTML('<div data-id="{{cat}}">
    <a href="http://google.com">Google</a>
</div>',LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

braces($dom->documentElement);

The var_dump() on this one does not find the attribute with {{ and }}.

Here is test case 1's resulting output:

object(DOMNodeList)#4 (1) {
  ["length"]=>
  int(0)
}

Test Case 2

$dom = new DOMDocument();
$dom->loadHTML('<div data-id="{{cat}}"></div>',LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

braces($dom->documentElement);

When removing the child a element, the var_dump() now can find the attribute with {{ and }}.

Here is test case 2's resulting output:

object(DOMNodeList)#3 (1) {
  ["length"]=>
  int(1)
}

So, my question is why can't it find the value when the item has children?

  • 写回答

1条回答 默认 最新

  • douke6424 2015-11-02 09:20
    关注

    Take another look at your predicate

    *=(contains(., "{{") and contains(., "}}"))
    

    This is an equality comparison with two operands. The right-hand operand is a boolean (A and B is always boolean). XPath 1.0, therefore, forces the left-hand operand to be a boolean as well. "*" selects the children of the context node; boolean(*) is true if that node-set is non-empty, that is, if the context node has one or more children.

    So your equality comparison is true if either (a) the node has children and contains braces, or (b) the node has no children and does not contain braces.

    What do I mean by contains here? The expression contains(., 'x') is true if the string value of the node contains 'x' as a substring. The string value of a node derives from the children/descendants of the node; it takes no account of attributes. Because it ignores attributes, your contains() test is false in both cases, so the predicate as a whole is true only if the left-hand operand is also false, that is, if the node has no children.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题