我正在处理这个link(40MB的可下载文件)中的XML文件。在这个文件中,我需要来自两种类型的标记的数据
它们是:OpportunityForecastDetail_1_0
和OpportunitySynopsisDetail_1_0
我为此编写了以下代码:
ARTICLE_TAGS = ['OpportunitySynopsisDetail_1_0', 'OpportunityForecastDetail_1_0']
for _tag in ARTICLE_TAGS:
f = open(xml_f)
context = etree.iterparse(f, tag = _tag)
for _, e in context:
_id = e.xpath('.//OpportunityID/text()')
text = e.xpath('.//OpportunityTitle/text()')
f.close()
然后etree.iterparse(f, tag = _tag)
返回一个不可iterable的对象。我认为在XML文件中找不到标记时会发生这种情况
所以,我在iterable标记中添加了名称空间,如下所示
context = etree.iterparse(f, tag='{http://apply.grants.gov/system/OpportunityDetail-V1.0}'+_tag)
现在,它正在创建一个iterable对象。但是,我没有收到任何短信。我尝试了那个文件中的其他名称空间。但是,不起作用
请告诉我这个问题的解决办法。这是XML文件的一个示例片段OpportunityForecastDetail_1_0
和OpportunitySynopsisDetail_1_0
标记在XML文件中重复n次
<?xml version="1.0" encoding="UTF-8"?>
<Grants xsi:schemaLocation="http://apply.grants.gov/system/OpportunityDetail-V1.0 https://apply07.grants.gov/apply/system/schemas/OppotunityDetail-V1.0.xsd" xmlns="http://apply.grants.gov/system/OpportunityDetail-V1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instace">
<OpportunitySynopsisDetail_1_0>
<OpportunityID>262148</OpportunityID>
<OpportunityTitle>Establishment of the Edmund S. Muskie Graduate Internship Program</OpportunityTitle>
</OpportunitySynopsisDetail_1_0>
<OpportunityForecastDetail_1_0>
<OpportunityID>284765</OpportunityID>
<OpportunityTitle>PPHF 2015: Immunization Grants-CDC Partnership: Strengthening Public Health Laboratories-financed in part by 2015 Prevention and Public Health Funds</OpportunityTitle>
</OpportunityForecastDetail_1_0>
</Grants>
首先,在解析包含名称空间的XML时,查看标记名时必须使用这些名称空间。
第二,
iterparse
不接受名为tag
的参数,因此我不知道您的代码在发布时是如何工作的。 最后,从iterparse
返回的元素没有名为xpath
的成员函数,因此这也不可能起作用下面是如何使用
iterparse
解析XML的示例:正如我在评论中所说,Python documentation和Effbot page on ElementTree一样有用。有很多其他可用的资源;把
xml.etree.elementtree
放进谷歌,开始阅读吧相关问题 更多 >
编程相关推荐