Python XPath / libxml2 namespace query

百般思念 提交于 2019-12-12 04:19:09

问题


I have been trying to parse the London Underground Linestatus XML "feed" - with little success. I would have expected this to ne "easy" using XPath, but I am getting empty nodes.

I am fairly sure sure that I am not dealing with the uk namespace correctly.

Here is my (rather simple code):

import libxml2
from urllib2 import urlopen

data = urlopen('http://cloud.tfl.gov.uk/TrackerNet/LineStatus').read()

try:
    doc = libxml2.parseDoc(data)
except (libxml2.parserError, TypeError):
    print "Problems loading XML"

context = doc.xpathNewContext()
context.xpathRegisterNs("uk", "http://webservices.lul.co.uk")

record_nodes = context.xpathEval('//uk:LineStatus')

for node in record_nodes:
    print "******************************"

The record_nodes loop is being ignored. The xml is being parsed correctly.

Can someone please shed some light on this.


回答1:


You need to add a forward slash at the end of the namespace URI. The correct URI is http://webservices.lul.co.uk/.



来源:https://stackoverflow.com/questions/8566111/python-xpath-libxml2-namespace-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!