首页 > 解决方案 > 如何将 XML 转换为 XML 文件中缺少某些值的 CSV?

问题描述

我有一个简单的 XML 数据,如下所示,

<LocationList>
  <Location dateTime="2018-11-17T00:11:01+09:00" x="2711.208" y="566.3292" z="0" motion="Walk" isMoving="True" stepCount="1" groupAreaId="1" commit="True" />
  <Location dateTime="2018-11-17T00:11:02+09:00" x="2640.506" y="518.7352" z="0" motion="Walk" isMoving="True" stepCount="1" groupAreaId="1" commit="True" />
  <Location dateTime="2018-11-17T00:11:03+09:00" x="2640.506" y="518.7352" z="0" motion="Stop" isMoving="False" stepCount="0" groupAreaId="1" />
  <Location dateTime="2018-11-17T00:52:31+09:00" x="2516.404" y="574.0547" z="0" motion="Walk" isMoving="True" stepCount="1" groupAreaId="1" />

我已经尝试将 XML 解析为 csv 文件,

import xml.etree.ElementTree as et
import csv

tree = et.parse('./1_2018-11-17.xml')
nodes = tree.getroot()
with open('testxml1.csv', 'w') as ff:
    cols = ['dateTime','x','y','z','motion','isMoving','stepCount',
            'groupAreaId','commit']
    nodewriter = csv.writer(ff)
    nodewriter.writerow(cols)
    for node in nodes:
        values = [ node.attrib[kk] for kk in cols]
        nodewriter.writerow(values)

但是,由于并非所有 XML 行都具有“stepCount”、“groupAreaId”、“commit”的值,因此除非我删除这些变量,否则代码将无法工作。

我如何能够获取 csv 文件中显示的所有变量,包括变量上具有空值的行?

标签: pythonxmlpandascsvelementtree

解决方案


如果您使用 .get() 方法读取节点属性,则可以添加默认值,例如空字符串。所以在你的情况下,它会是这样的:

for node in nodes:
        values = [ node.attrib.get(kk, '') for kk in cols]
        nodewriter.writerow(values)

推荐阅读