【发布时间】:2015-01-15 12:03:09
【问题描述】:
我找不到信息,如何使用命名空间解析我的 XML:
我有这个 xml:
<par:Request xmlns:par="http://somewhere.net/actual">
<par:actual>blabla</par:actual>
<par:documentType>string</par:documentType>
</par:Request>
并试图解析它:
dom = ET.parse(u'C:\\filepath\\1.xml')
rootxml = dom.getroot()
for subtag in rootxml.xpath(u'//par:actual'):
#do something
print(subtag)
得到了异常,因为它不知道命名空间前缀。 有没有最好的方法来解决这个问题,计算脚本不会知道它要解析的文件和标签要搜索的文件?
搜索网页和stackoverflow我发现,如果我会在那里添加:
namespace = {u'par': u"http://somewhere.net/actual"}
for subtag in rootxml.xpath(u'//par:actual', namespaces=namespace):
#do something
print(subtag)
这行得通。完美的。但我不知道我将解析哪个 XML,并且我的脚本也不知道搜索标记(例如 //par:actual)。所以,我需要想办法从 XML 中提取命名空间。
我找到了很多方法,如何提取命名空间URI,比如:
print(rootxml.tag)
print(rootxml.xpath('namespace-uri(.)'))
print(rootxml.xpath('namespace-uri(/*)'))
但是我应该如何提取前缀来创建 ElementTree 想要的字典呢?我不想在 xml 正文上使用正则表达式怪物来提取前缀,我相信必须存在支持的方式,不是吗?
也许必须存在一些方法让我通过 ETree 命名空间从 XML 中提取为字典(正如 ETree 所希望的那样!)而无需手动操作?
【问题讨论】:
标签: python xml-namespaces elementtree prefix