Reputation: 11
I am having trouble with an XPath query. I am using //link[@rel='alternate']
but this returns a null nodeset. I am trying to write a query that will select the value of the href attribute for all link nodes where rel=alternate
What am I doing wrong?
Below is a simplified sample of the xml structure I am working with.
<feed>
<entry>
<id>1980475</id>
<link rel="post" href="http://..."></link>
<link rel="edit" href="http://..."></link>
<link rel="alternate" href="http://..."></link>
</entry>
<entry>
<id>1980476</id>
<link rel="post" href="http://..."></link>
<link rel="edit" href="http://..."></link>
<link rel="alternate" href="http://..."></link>
</entry>
</feed>
Here is the php code I am using as well:
$xmlDoc = simplexml_load_file("somefile.xml");
$nodelist = $xmlDoc->xpath("//link[@rel='alternate']");
Upvotes: 1
Views: 3731
Reputation: 27994
As @Jens noted, you're probably processing an Atom feed. XML elements in Atom are in the Atom namespace, whose URI is http://www.w3.org/2005/Atom
.
You need to register that namespace and use it in your XPath expression. See this answer on how to do that.
When you posted a "simplified sample" of the input XML, you presumably removed the default namespace declaration, as in
<feed xmlns="http://www.w3.org/2005/Atom">
This seemingly insignificant change means that <feed>
and all the all elements descended from it are in no namespace, whereas in the real input data, they are in the Atom namespace. That would explain why your XPath expression works when tested on the sample input (as @Passerby said), but doesn't work on the real input.
If you register a
as the namespace prefix for the Atom namespace, as shown in the answer I linked to above, your XPath expression will be:
xpath("//a:link[@rel='alternate']")
Upvotes: 1