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

2024-10-01 13:38:25 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我正在工作的医生的样本:

<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”的所有节点:

^{pr2}$

这将返回3namespace元素的列表。但是如果我想得到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属性中的字符串。不幸的是,语法不是很正确,我很难从文档中获得正确的语法。谢谢您!在


Tags: orghttpindex属性schemawwwnamespaceresource
1条回答
网友
1楼 · 发布于 2024-10-01 13:38:25

我想你想要的是:

//*[local-name()="namespace"]/@idx:resourceLocation

或者

^{pr2}$

或者,如果只需要那些以"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

相关问题 更多 >