使用 Expat 在 Python 中解析 XML
背景:我来自 C# 领域,所以我正在寻找诸如能够通过 Xpath 选择来处理节点和值之类的东西。
到目前为止,这是我的代码:
import urllib
import sys
from xml.parsers import expat
url = 'http://SomeWebService.SomeDomain.com'
u = urllib.urlopen(url)
Parser = expat.ParserCreate()
data = u.read()
try:
Parser.Parse(data)
except:
print "ERROR: Can't parse the XML"
sys.exit(0)
我应该使用什么标准库来像 C# 中那样将 DOM 元素作为对象及其属性来处理?
我正在寻找类似 NodeList Nodes = Parser.SelectNodes("Xpath") 的东西
Background: I'm coming from C#-land, so I'm looking for something like being able to handle nodes and values by selecting via Xpath.
Here's my code, so far:
import urllib
import sys
from xml.parsers import expat
url = 'http://SomeWebService.SomeDomain.com'
u = urllib.urlopen(url)
Parser = expat.ParserCreate()
data = u.read()
try:
Parser.Parse(data)
except:
print "ERROR: Can't parse the XML"
sys.exit(0)
What standard lib should I be using to deal with DOM elements as objects along with their attributes as one could in C#?
I'm looking for something like NodeList nodes = Parser.SelectNodes("Xpath")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果您尝试使用
xml.dom
包或xml.etree.ElementTree
。 ElementTree 对 xpath 支持有一些有限,所以如果您习惯的话,它可能是最好的选择。I think you would have more luck if you tried using one of the
xml.dom
packages, orxml.etree.ElementTree
. ElementTree has some limited xpath support, so if that's what you're used to, it might be the best choice.