在Python中解析嵌套的复杂XML

如何解决在Python中解析嵌套的复杂XML

我正在尝试解析非常复杂的xml文件,并将其内容存储在dataframe中。我尝试了xml.etree.ElementTree,并设法检索了一些元素,但是以某种方式多次检索它,就好像有更多对象一样。我正在尝试提取以下内容:category,created,last_updated,accession type,name type identifier,name type synonym as a list

<cellosaurus>
<cell-line category="Hybridoma" created="2012-06-06" last_updated="2020-03-12" entry_version="6">
  <accession-list>
    <accession type="primary">CVCL_B375</accession>
  </accession-list>
  <name-list>
    <name type="identifier">#490</name>
    <name type="synonym">490</name>
    <name type="synonym">Mab 7</name>
    <name type="synonym">Mab7</name>
  </name-list>
  <comment-list>
    <comment category="Monoclonal antibody target"> Cronartium ribicola antigens </comment>
    <comment category="Monoclonal antibody isotype"> IgM,kappa </comment>
  </comment-list>
  <species-list>
    <cv-term terminology="NCBI-Taxonomy" accession="10090">Mus musculus</cv-term>
  </species-list>
  <derived-from>
    <cv-term terminology="Cellosaurus" accession="CVCL_4032">P3X63Ag8.653</cv-term>
  </derived-from>
  <reference-list>
    <reference resource-internal-ref="Patent=US5616470"/>
  </reference-list>
  <xref-list>
    <xref database="CLO" category="Ontologies" accession="CLO_0001018">
      <url><![CDATA[https://www.ebi.ac.uk/ols/ontologies/clo/terms?iri=http://purl.obolibrary.org/obo/CLO_0001018]]></url>
    </xref>
    <xref database="ATCC" category="Cell line collections" accession="HB-12029">
      <url><![CDATA[https://www.atcc.org/Products/All/HB-12029.aspx]]></url>
    </xref>
    <xref database="Wikidata" category="Other" accession="Q54422073">
      <url><![CDATA[https://www.wikidata.org/wiki/Q54422073]]></url>
    </xref>
  </xref-list>
</cell-line>
</cellosaurus>

解决方法

解析XML的最简单方法是IMHO,使用lxml。

from lxml import etree
data = """[your xml above]"""
doc = etree.XML(data)
for att in doc.xpath('//cell-line'):
    print(att.attrib['category'])
    print(att.attrib['last_updated'])
    print(att.xpath('.//accession/@type')[0])
    print(att.xpath('.//name[@type="identifier"]/text()')[0])
    print(att.xpath('.//name[@type="synonym"]/text()'))

输出:

Hybridoma
2020-03-12
primary
#490
['490','Mab 7','Mab7']

然后您可以将输出分配给变量,追加到列表等

,

鉴于在某些情况下您希望解析标记属性,而在另一些情况下您想要解析tag_values,因此您的问题还不清楚。

我的理解如下。您需要以下值:

  1. 标签 cell-line 的属性 category 的值。
  2. 标记 cell-line created 属性的值。
  3. 标签 cell-line 的属性 last_updated 的值。
  4. 标签 accession 的属性 type 的值。
  5. 与具有属性 identifier 的标签 name 相对应的文本。
  6. 与具有属性同义词的标签 name 对应的文本。

可以使用模块xml.etree.Etree从xml文件中提取这些值。尤其要注意使用Element类的findalliter方法。

假设xml位于名为 input.xml 的文件中,则以下代码段即可解决问题。

import xml.etree.ElementTree as et


def main():
    tree = et.parse('cellosaurus.xml')
    root = tree.getroot()

    results = []
    for element in root.findall('.//cell-line'):
        key_values = {}
        for key in ['category','created','last_updated']:
            key_values[key] = element.attrib[key]
        for child in element.iter():
            if child.tag == 'accession':
                key_values['accession type'] = child.attrib['type']
            elif child.tag == 'name' and child.attrib['type'] == 'identifier':
                key_values['name type identifier'] = child.text
            elif child.tag == 'name' and child.attrib['type'] == 'synonym':
                key_values['name type synonym'] = child.text
        results.append([
                # Using the get method of the dict object in case any particular
                # entry does not have all the required attributes.
                 key_values.get('category',None),key_values.get('created',key_values.get('last_updated',key_values.get('accession type',key_values.get('name type identifier',key_values.get('name type synonym',None)
                ])

    print(results)


if __name__ == '__main__':
    main()
,

另一种方法。最近,我比较了几个XML解析库,发现它易于使用。我推荐。

from simplified_scrapy import SimplifiedDoc,utils

xml = '''your xml above'''
# xml = utils.getFileContent('your file name.xml')

results = []
doc = SimplifiedDoc(xml)
for ele in doc.selects('cell-line'):
  key_values = {}
  for k in ele:
    if k not in ['tag','html']:
      key_values[k]=ele[k]
  key_values['name type identifier'] = ele.select('name@type="identifier">text()')
  key_values['name type synonym'] = ele.selects('name@type="synonym">text()')
  results.append(key_values)
print (results)

结果:

[{'category': 'Hybridoma','created': '2012-06-06','last_updated': '2020-03-12','entry_version': '6','name type identifier': '#490','name type synonym': ['490','Mab7']}]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-