我有以下想要使用 Python 的 ElementTree
解析的 XML:
<rdf:RDF xml:base="http://dbpedia.org/ontology/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns="http://dbpedia.org/ontology/">
<owl:Class rdf:about="http://dbpedia.org/ontology/BasketballLeague">
<rdfs:label xml:lang="en">basketball league</rdfs:label>
<rdfs:comment xml:lang="en">
a group of sports teams that compete against each other
in Basketball
</rdfs:comment>
</owl:Class>
</rdf:RDF>
我想找到所有 owl:Class
标签,然后提取其中所有 rdfs:label
实例的值。我正在使用以下代码:
tree = ET.parse("filename")
root = tree.getroot()
root.findall('owl:Class')
由于命名空间,我收到以下错误。
SyntaxError: prefix 'owl' not found in prefix map
我尝试阅读 http://effbot.org/zone/element-namespaces.htm 上的文档但由于上述 XML 有多个嵌套命名空间,因此我仍然无法正常工作。
请告诉我如何更改代码以找到所有 owl:Class
标记。
最佳答案
你需要给 .find()
、findall()
和 iterfind()
方法一个显式的命名空间字典:
namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed
root.findall('owl:Class', namespaces)
前缀只在你传入的namespaces
参数中查找。这意味着你可以使用任何你喜欢的命名空间前缀; API 分离出 owl:
部分,在 namespaces
字典中查找相应的命名空间 URL,然后更改搜索以查找 XPath 表达式 {http://www.w3.org/2002/07/owl}Class
代替。当然,您也可以自己使用相同的语法:
root.findall('{http://www.w3.org/2002/07/owl#}Class')
另见 Parsing XML with Namespaces section ElementTree 文档。
如果可以切换到lxml
library事情变得更好了;该库支持相同的 ElementTree API,但在元素的 .nsmap
属性中为您收集命名空间,并且通常具有出色的命名空间支持。
关于python - 通过 'ElementTree' 在 Python 中使用命名空间解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14853243/