gpt4 book ai didi

python - XPath - 返回具有特定字符串模式的所有节点

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:17 24 4
gpt4 key购买 nike

这是我正在使用的文档中的示例:

<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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com