2

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

<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 文档作为指南的尝试。

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属性中的那些字符串。不幸的是,语法不太正确,我无法从文档中获取正确的语法。谢谢!

4

1 回答 1

2

我认为您正在寻找的是:

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

或者

//idx:namespace/@idx:resourceLocation

或者,如果你只想要那些以你@idx:resourceLocation开头的属性,"http://resource.belframework.org/belframework/1.0/namespace"你可以使用

'''//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
于 2013-07-15T22:02:59.310 回答