解析的XML使用Python/ET
问题描述:
我有大意如下XML特定的元素:解析的XML使用Python/ET
<?xml version="xxx"?>
<doc:document xmlns:doc="some value 1...">
<rdf:RDF xmlns:rdf="some value 2...">
<rdf:Description rdf:about="some value...">
<dct:format xmlns:dct="http://someurl/">some value 3</dct:format>
<dct:title xmlns:dct="http://someurl/">some text of interest to me</dct:title>
</rdf:Description>
</rdf:RDF>
</doc:document>
我如何得到“一些感兴趣的文字给我”使用Python/ETree?
在此先感谢您的帮助!
答
你需要去寻找title
元素通过指定的命名空间:
tree.find('.//dct:title', namespaces={'dct': 'http://purl.org/dc/terms/'})
您有在每个搜索一个namespaces
映射通过,所以你也可以只指定了前面,重用:
nsmap = {
'dct': 'http://purl.org/dc/terms/',
'doc': 'http://www.witbd.org/xmlns/common/document/',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
}
tree.find('.//dct:title', namespaces=nsmap)
对于您的示例文件(与恢复的命名空间),给出:
>>> tree.find('.//dct:title', namespaces=nsmap)
<Element '{http://purl.org/dc/terms/}title' at 0x105ec4690>
>>> tree.find('.//dct:title', namespaces=nsmap).text
'some text of interest to me'
你也可以使用该命名空间中的XPath表达式:
tree.find('.//{http://purl.org/dc/terms/}title')
这是使用什么前缀和namespaces
地图内部确实反正。
非常感谢您的帮助。 – user7289 2013-03-13 15:59:48
顺便说一下,这个方法在导入cElementTree时不起作用;只有ElementTree – user7289 2013-03-19 15:53:12