python - 如何将 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 文件中显示的所有变量,包括变量上具有空值的行?
解决方案
如果您使用 .get() 方法读取节点属性,则可以添加默认值,例如空字符串。所以在你的情况下,它会是这样的:
for node in nodes:
values = [ node.attrib.get(kk, '') for kk in cols]
nodewriter.writerow(values)
推荐阅读
- java - 将字符串的一部分变成可点击的链接
- c# - 第一次单击异步按钮时,UI 冻结 5 秒
- c++ - 读取整数的二进制文件
- python - 基于多个事件的Django调用函数
- java - getresource() 空指针的问题
- arrays - 无法正确循环数组条件失败-reactjs
- java - 有没有办法在运行时访问和修改 Eclipse 插件的源代码?
- java - 无需遍历所有像素即可替换图像中的颜色
- java - java是否可以在数组中插入算术运算符(+ - / *)?
- laravel - 在新的 laravel 文件中执行“npm run”时出错 - 找不到模块 npm-cli.js