【问题标题】:How do I convert XML to CSV with some missing value in XML file?如何将 XML 转换为 XML 文件中缺少某些值的 CSV?
【发布时间】:2019-11-15 08:32:03
【问题描述】:

我有一个简单的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 文件中显示的所有变量,包括变量上具有空值的行?

【问题讨论】:

    标签: python xml pandas csv elementtree


    【解决方案1】:

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

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

    【讨论】:

    • 另外,我知道应该在不同的问题中提出,但是如何从多个 xml 中获取多个 csv 输出?我尝试了 glob,但效果不佳..
    • @npm 应该在另一个问题中询问,但如果您想循环浏览文件,可以查看:stackoverflow.com/questions/10377998/…
    【解决方案2】:

    您可以在列表推导中使用 if-else 语句来检查属性是否存在。

    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:
            # if kk is not an attribute, set the value to None
            values = [node.attrib[kk] if kk in node.attrib else None for kk in cols]
            # Replace commit value with false if it does not exist
            if values[-1] is None:
                values[-1] = False
            nodewriter.writerow(values)
    

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 1970-01-01
      • 2023-03-06
      • 2011-03-05
      • 2015-10-28
      • 2014-11-22
      • 2017-04-18
      • 1970-01-01
      相关资源
      最近更新 更多