简体   繁体   English

DomXPath选择

[英]DomXPath Selecting

I have a problem with the DomXPath for selecting what I need. 我在选择所需的DomXPath时遇到问题。 I have a structure like 我有一个像

<div id="a">
  Something
    <nobr> Inside </nobr>
</div>

What I want is to select only 'Something' not 'Inside'. 我想要的是仅选择“某物”而不是“内部”。 I know how to select only 'Inside' or both of them in the same time like //div[@id='a'] and then call $obj->nodeValue , but I couldn't find a way to select only 'Something'. 我知道如何像//div[@id='a']一样同时选择'Inside'或它们两者,然后调用$obj->nodeValue ,但是我找不到唯一选择'东西。 Could anyone help me about this? 有人可以帮我吗? Thanks. 谢谢。

Edit: If Something is changed to Something 123456 can you also give me a hint how to select only numeric values as 123456 as a bonus? 编辑:如果将Something更改为Something 123456,您还可以提示我如何仅选择数字值作为123456作为奖励吗?

To locate the number inside the text node in xpath is quite heavy. 在xpath的文本节点内定位数字非常繁琐。 Instead you can use a regular expression in PHP to parse the textnode's text to obtain the value: 相反,您可以在PHP中使用正则表达式来解析textnode的文本以获得值:

$doc = new DomDocument;
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$text = $xpath->query("/div[@id='a']/child::text()")->item(0)->nodeValue;
$r = preg_match('~\d+~', $text, $matches);
list($number) = $matches;

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM