这是我正在使用的文档中的示例:
<idx:index xsi:schemaLocation="http://www.belscript.org/schema/index index.xsd" idx:belframework_version="2.0">
<idx:namespaces>
<idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/entrez-gene-ids-hmr.belns"/>
<idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/hgnc-approved-symbols.belns"/>
<idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/mgi-approved-symbols.belns"/>
我可以使用以下代码获取名称为“namespace”的所有节点:
tree = etree.parse(self.old_files)
urls = tree.xpath('//*[local-name()="namespace"]')
这将返回 3 个 namespace
元素的列表。但是,如果我想获取 idx:resourceLocation 属性中的数据怎么办?这是我尝试使用 XPath docs 来做到这一点作为指导。
urls = tree.xpath('//*[local-name()="namespace"]/@idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/"',
namespaces={'idx' : 'http://www.belscript.org/schema/index'})
我想要的是具有以http://resource.belframework.org/belframework/1.0/namespace
开头的属性的所有节点。因此,在示例文档中,它只会返回 resourceLocation
属性中的那些字符串。不幸的是,语法不太正确,并且我无法从文档中得出正确的语法。谢谢!
最佳答案
我认为您正在寻找的是:
//*[local-name()="namespace"]/@idx:resourceLocation
或
//idx:namespace/@idx:resourceLocation
或者,如果您只需要那些以 "http://resource.belframework.org/belframework/1.0/namespace"
开头的 @idx:resourceLocation
属性,您可以可以使用
'''//idx:namespace[
starts-with(@idx:resourceLocation,
"http://resource.belframework.org/belframework/1.0/namespace")]
/@idx:resourceLocation'''
import lxml.etree as ET
content = '''\
<root xmlns:xsi="http://www.xxx.com/zzz/yyy" xmlns:idx="http://www.belscript.org/schema/index">
<idx:index xsi:schemaLocation="http://www.belscript.org/schema/index index.xsd" idx:belframework_version="2.0">
<idx:namespaces>
<idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/entrez-gene-ids-hmr.belns"/>
<idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/hgnc-approved-symbols.belns"/>
<idx:namespace idx:resourceLocation="http://resource.belframework.org/belframework/1.0/namespace/mgi-approved-symbols.belns"/>
</idx:namespaces>
</idx:index>
</root>
'''
root = ET.XML(content)
namespaces = {'xsi': 'http://www.xxx.com/zzz/yyy',
'idx': 'http://www.belscript.org/schema/index'}
for item in root.xpath(
'//*[local-name()="namespace"]/@idx:resourceLocation', namespaces=namespaces):
print(item)
产量
http://resource.belframework.org/belframework/1.0/namespace/entrez-gene-ids-hmr.belns
http://resource.belframework.org/belframework/1.0/namespace/hgnc-approved-symbols.belns
http://resource.belframework.org/belframework/1.0/namespace/mgi-approved-symbols.belns
关于python - XPath - 返回具有特定字符串模式的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17664556/