Я хотел бы преобразовать этот XML файл:
<record id="idOne">
<ts date="2019-07-03" time="15:28:41.720440">5</ts>
<ts date="2019-07-03" time="15:28:42.629959">10</ts>
<ts date="2019-07-03" time="15:28:43.552677">15</ts>
<ts date="2019-07-03" time="15:28:43.855345">20</ts>
</record>
<record id="idOne">
<ts date="2019-07-03" time="15:28:45.072922">30</ts>
<ts date="2019-07-03" time="15:28:45.377087">35</ts>
<ts date="2019-07-03" time="15:28:46.316321">40</ts>
<ts date="2019-07-03" time="15:28:47.527960">45</ts>
</record>
в этот CSV-файл:
ID, date, time, value
idOne, 2019-07-03, 15:28:41.720440, 5
idOne, 2019-07-03, 15:28:42.629959, 10
idOne, 2019-07-03, 15:28:43.552677, 15
idOne, 2019-07-03, 15:28:43.855345, 20
idOne, 2019-07-03, 15:28:45.072922, 30
idOne, 2019-07-03, 15:28:45.377087, 35
idOne, 2019-07-03, 15:28:46.316321, 40
idOne, 2019-07-03, 15:28:47.527960, 45
У меня может быть несколько тел структур идентификаторов.
Я использую библиотеку l xml.
Я пробовал использовать метод xpath и l oop, но я могу получить только идентификатор, но не остальные. Проблема вторая для l oop, но я не знаю, как обращаться со значениями «дата» и «время» ...
with open(args.input, "r") as f:
# add root balises to parse the xml file
records = itertools.chain('<root>', f, '</root>')
root = etree.fromstringlist(records)
#root = etree.fromstring(records)
# count the number of records
NumberRecords = int(root.xpath('count(//record)'))
RecordsGrid = [[] for __ in range(NumberRecords)]
tss = ["id","date", "time", "value"]
paths = root.xpath('//record')
#print(paths)
Counter = 0
for path in paths:
for ts in tss[:1]:
target = f'(./@{ts})' # using f-strings to populate the full path
if path.xpath(target):
# we start populating our current sublist with the relevant info
RecordsGrid[Counter].append(path.xpath(target)[0])
else:
RecordsGrid[Counter].append('NA')
for ts in tss[1:]:
target = f'(./ts[@name="{ts}"]/text())'
if path.xpath(target):
RecordsGrid[Counter].append(path.xpath(target)[0])
else:
RecordsGrid[Counter].append('NA')
Counter += 1
# now that we have our lists, create a df
df = pd.DataFrame(RecordsGrid, columns=tss)
df.to_csv(args.output, sep=',', encoding='utf-8', index=False)
Вот результат:
id,date,time,value
idOne,NA,NA,NA
Спасибо за ваше время.