Python中用元素树解析XML

2024-04-25 09:49:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python中的元素树来解析XML文件。我附上了一张快照XML data。我需要拉所有的时间序列标签下的东西,并将其导出为CSV。你知道吗

我已将文件保存到我的计算机上,因此得名保存.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')

如何获取位于timeseries标记下的所有内容并将其导出为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)

Tags: 文件csvintree密码rootxmlfind
1条回答
网友
1楼 · 发布于 2024-04-25 09:49:44
#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')

相关问题 更多 >

    热门问题