XPath blues

This is probably better suited for an XML forum, but given it is in the context of Plex I’ll ask anyhow:



I have an XML file in XSPF format, and I am trying to get the tracks using xpath, but for the life of me I can’t work out what the trick is. The file looks something like:



<?xml version="1.0" encoding="UTF-8"?><br />
<playlist version="1" xmlns="http://xspf.org/ns/0/"><br />
	<title>My Playlist</title><br />
	<trackList><br />
		<track><br />
			<title>hello world</title><br />
			<image>http://.../</image><br />
			<location>file:///.../</location><br />
		</track><br />
	</trackList><br />
</playlist>


The relevant code I am using is:


xml =  XML.ElementFromURL(XSPF_URL, errors='ignore')<br />
feed = xml.xpath('//playlist/trackList/track')


but this always returns 0 elements.

I can confirm that the root node indeed has two children with:


Log('size: ' + str( len(xml.getchildren()) ) )


Can anyone suggest what I should be doing to get a list of the track elements? I suspect this might have something to do with the anonymous name space, but I can't quite figure it out.

have you tried //playlist//trackList//track,

also, depending on what else is in the xml, just ‘//track’ could work

for more specific help than that id need to see the actual xml

if you’re not already, you should use the xpather firefox plugin, it makes this so much easier

Or try it with a lowercase L in tracklist:


feed = xml.xpath('//playlist/tracklist/track')


I ran into a similar problem once with "pubDate" versus "pubdate".


The case is correct, as described in the specification:

[http://www.xspf.org/xspf-v1.html](http://www.xspf.org/xspf-v1.html)

it is inconsistent, when you compare 'playlist' and 'trackList', but that's the way it is defined.

Finally after a bit of help with 'XPath Checker' (seemed better than xpather) and some experimenting:


myNamespaces = {'ns1':'http://xspf.org/ns/0/'}<br />
items = xml.xpath('//ns1:track',namespaces=myNamespaces )<br />
<br />
for item in items:<br />
   title = item.xpath('ns1:title',namespaces=myNamespaces )[0].text


Even if the namespace is not prefixed, you still need to declare a mapping, since it is still mapped. It is the URL of the namespace that is significant, not the alias.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.