Skip to main content
 首页 » 编程设计

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

2024年11月01日22haluo1

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

<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