0

我有一个 XML 文件,其结构类似于以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<drugbank xmlns="http://www.drugbank.ca" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.drugbank.ca http://www.drugbank.ca/docs/drugbank.xsd" version="5.0" exported-on="2017-12-20">
    <drug type="biotech" created="2005-06-13" updated="2017-11-06">
        <drugbank-id primary="true">DB00001</drugbank-id>
        <drugbank-id>BTD00024</drugbank-id>
        <drugbank-id>BIOD00024</drugbank-id>
        <cas-number>138068-37-8</cas-number>
        <name>Lepirudin</name>
    </drug>
    <drug type="biotech" created="2005-06-13" updated="2017-11-06">
        <drugbank-id primary="true">DB00045</drugbank-id>
        <drugbank-id>BTD00054</drugbank-id>
        <drugbank-id>BIOD00054</drugbank-id>
        <cas-number>205923-56-4</cas-number>
        <name>Lyme disease vaccine (recombinant OspA)</name>
    </drug>
</drugbank>

我正在尝试使用 Python 3 的 cElementTree 模块。我想提取此 XML 中每种药物的名称,为此我编写了以下代码:

import xml.etree.cElementTree as ET

tree = ET.parse('fulldatabase.xml')
drugbank = tree.getroot()

print(drugbank.tag)

for drug in drugbank:
    print(drug.find('name').text)

我得到的错误是AttributeError: 'NoneType' object has no attribute 'text'

我也尝试过检查但 OP 在其中写的答案对我不起作用。有什么方法可以让每种药物都消失namecas-number我已经尝试了一些组合,比如findall()在 for 循环条件中删除,但即使在那时,事情也对我不起作用。

4

1 回答 1

2

Do you need anything besides the name? If not this will do it. You're not using the xml namespace properly as defined in the <drugbank xmlns="http://www.drugbank.ca" portion of the file

for drug in drugbank.iter('{http://www.drugbank.ca}name'):
    print drug.text

Lepirudin
Lyme disease vaccine (recombinant OspA)

Here's another way to get the elements you need:

for child in drugbank.getchildren():
    print {'cas-number': child.find('{http://www.drugbank.ca}cas-number').text, 'name': child.find('{http://www.drugbank.ca}name').text}

{'cas-number': '138068-37-8', 'name': 'Lepirudin'}
{'cas-number': '205923-56-4', 'name': 'Lyme disease vaccine (recombinant OspA)'}
于 2018-04-11T15:24:19.537 回答