2014-04-01 76 views
1

有一个Xpath问题的真正问题。我试图将节点与一定的值进行匹配。PHP XPath问题

这是一个示例XML片段。

http://pastie.org/private/xrjb2ncya8rdm8rckrjqg

我想匹配给定MatchNumber节点值,看看是否有两个或两个以上。假设这存储在一个名为$ data的变量中,我使用下面的表达式。自从我做了很多XPath以来,这已经有一段时间了,因为现在大多数事情似乎都是JSON,所以请原谅任何新手的疏忽。

$doc = new DOMDocument; 
$doc->load($data); 
$xpath = new DOMXPath($doc); 
$result = $xpath->query("/CupRoundSpot/MatchNumber[.='1']"); 

我需要基本上匹配具有1的匹配号码值的任何节点,然后确定该结果长度大于1(即2个或更多已被发现)。

非常感谢您的任何帮助。

回答

3

你的XML文档有一个默认的命名空间:xmlns="http://www.fixtureslive.com/"
您必须在xpath元素上使用register this namespace并在查询中使用(注册)前缀。

$xpath->registerNamespace ('fl' , 'http://www.fixtureslive.com/'); 
$result = $xpath->query("/fl:ArrayOfCupRoundSpot/fl:CupRoundSpot/fl:MatchNumber[.='1']"); 
foreach($result as $e) { 
    echo '.'; 
} 
+0

干杯。我试过运行,但仍然没有匹配/结果。非常令人沮丧! – user343035

+0

$ doc-> loadXML($ data);是什么工具的问题!干杯! – user343035

0

以下XPath:

/CupRoundSpot[MatchNumber = 1] 

返回所有CupRoundSpot节点,其中MatchNumber等于1。你可以futher使用这些节点在PHP做的东西吧。

执行:

count(/CupRoundSpot[MatchNumber = 1]) 

返回你发现总CupRoundSpot节点,其中MatchNumber等于1

+0

干杯。我试过运行,但仍然没有匹配/结果。非常令人沮丧! – user343035

0

您必须注册命名空间。之后,您可以使用Xpath count()函数。像这样的表达只适用于evaluate(),而不适用于query()query()只能返回节点列表,而不是标量值。

$dom = new DOMDocument(); 
$dom->loadXml($xml); 
$xpath = new DOMXpath($dom); 
$xpath->registerNamespace('fl', 'http://www.fixtureslive.com/'); 

var_dump(
    $xpath->evaluate(
    'count(/fl:ArrayOfCupRoundSpot/fl:CupRoundSpot[number(fl:MatchNumber) = 1])' 
) 
); 

输出:

float(2) 

DEMO:https://eval.in/130366

要遍历CupRoundSpot节点,只要使用的foreach:

$nodes = $xpath->evaluate(
    '/fl:ArrayOfCupRoundSpot/fl:CupRoundSpot[number(fl:MatchNumber) = 1]' 
); 
foreach ($nodes as $node) { 
    //... 
}