【发布时间】:2020-08-07 21:17:44
【问题描述】:
我正在尝试解析具有以下结构的 XML 文件(在 Python 中,这对我来说是新的):
<xml>
<document>
<fit>
<grp> some tags </grp>
<prp>
<p> <id> 1674 </id> </p>
<drp>
<name> Joe </name>
<post>
<company> abc </company>
<company> Ltd. </company>
</post>
</drp>
</prp>
</fit>
</document>
<document>
.
.
.
</xml>
为了提取 id、name、company 等信息,然后将它们写入 csv,我尝试了以下代码:
tree = ET.parse(file)
root=tree.getroot()
with open(csvfile, 'a') as f:
writer=csvDictWriter(f, ['ID', 'NAME', 'NCOMP'], delimiter=', ')
writer.writeheader()
result = {}
for child in root.findall('./fit'):
result['ID'] = ( "" .join(child.find('p').find('id').text))
result['NAME'] = ( "" .join(child.find('drp').find('name'))
result['NCOMP'] = ( "" .join(child.find('drp').find('post').find('company')
writer.write(result)
但是,对于公司名称,我只获取第一个标签的内容,然后我尝试使用 for 循环并附加到这样的列表:
Com = []
for each in child.find('drp').find('post'):
coms = each.find('company')
Com = Com.append[coms]
result['NCOMP'] = Com
期望的输出:
ID. NAME. NCOMP
1674. Joe. abc Ltd.
如何更改代码以使其包含两个标签的值?
【问题讨论】:
-
欢迎来到stackoverflow!精心设计的第一个问题:)
标签: xml csv xml-parsing elementtree python-2.6