I am trying to use PHP and XPath to grab all the Category nodes with an ID element of 1364 from this XML: http://education.oracle.co.uk/html/oracle/28US/schedule.xml
My code is currently looking 开发者_如何学Pythonlike this:
$schedule = new SimpleXMLElement("schedule.xml", null, true);
$nodes = $schedule->xpath("//category[id=1364]");
if(!$nodes) {
echo "No xpath results.";
} else {
echo count($nodes)." results.";
}
The XPath returns no results. I have checked the query using other XPath query programs, and a result was returned.
The above code uses SimpleXML, but I have experienced exactly the same problem when using DOMDocument. In both SimpleXML and DOMDocument, running an XPath of "//*" works, returning all nodes in the document.
Thanks!
A wild guess, this is a namespace issue
Your XML document probably contains something like this
<root xmlns="http://some.uri">
<category id="1364"/>
</root>
Because <category>
is in the default namespace it does not have any prefix but in order to your XPath to work, you need to bind also this namespace to some prefix and then use that prefix in your XPath expression.
$schedule->registerXPathNamespace("ns", "http://some.uri");
$nodes = $schedule->xpath('//ns:category[id=1364]');
XPath (1.0) expressions without a namespace prefix always match only to targets in no-namespace.
精彩评论