【问题标题】:Parsing XML with Element Tree in Python在 Python 中使用元素树解析 XML
【发布时间】:2019-10-26 11:09:26
【问题描述】:

我试图在 python 中使用元素树来解析 XML 文件。我附上了一张快照XML data。我需要提取 TimeSeries 标签下的所有内容并将其导出为 CSV。

我已将文件保存到我的计算机上,因此代码中的名称为 save.xml。我试图以 mRID 和 CurveType 为例,但这对我不起作用。这是我试过的代码。

import xml.etree.cElementTree as ET

tree = ET.parse('save.xml')
root = tree.getroot()

for TimeSeries in root.findall('TimeSeries'):
    mRID = TimeSeries.find('mRID').text
    curve = TimeSeries.get ('curveType')

我如何抓取时间序列标签下的所有内容并导出为 CSV?

--为任何有相同问题的人编辑--

代码现在变成了这样,因为我们需要在标签的前面添加命名空间(或者删除它,如果这更容易的话):

#fix namespace issue
ns = {'s': 'urn:iec62325.351:tc57wg16:451-6:generationloaddocument:3:0'}

# use s and namespace in front of all findall

for TimeSeries in root.findall('s:TimeSeries', ns):
    mRID = TimeSeries.find('s:mRID', ns)
    businessType = TimeSeries.find('s:businessType', ns)
    objectAggregation = TimeSeries.find('s:objectAggregation', ns)
    unit = TimeSeries.find('s:quantity_Measure_Unit.name', ns)
    curveType = TimeSeries.find('s:curveType', ns)

【问题讨论】:

  • 该 URL 不可访问。此外,您应该在这里明确提出问题。
  • 我附上了图像形式的数据快照。我想知道如何获取 TimeSeries 下的所有数据并导出为 CSV。
  • 图片不是很有帮助,因为它不允许任何人轻松测试/重现您的问题。但是查看屏幕截图,我看到您的 xml 有一个默认命名空间(xmlns)尝试在 ElementTree 默认命名空间上搜索;有很多例子。如果您仍有问题,请更新您的问题,我们很乐意为您提供帮助。

标签: python xml parsing xml-parsing elementtree


【解决方案1】:
#Something like this can be done to fetch the data from xml file`enter code here`
import xml.etree.ElementTree as etree
tree = etree.patse('save.xml')
root = tree.getroot()
for timeseries in root.iter():
    print timeseries.get('mRID')
    print timeseries.get('curveType')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多