gpt4 book ai didi

python - 从 Excel 创建动态嵌套 xml

转载 作者:行者123 更新时间:2023-12-01 06:37:35 24 4
gpt4 key购买 nike

我正在尝试将 Excel 转换为嵌套 XML,但未能按预期成功。

这是我的代码。

import openpyxl
import xml.etree.ElementTree as etree

# reading data from the source, xls
wb1 = openpyxl.load_workbook(filename='C:\GSH\parent_child.xlsx')
ws1 = wb1.get_sheet_by_name('Sheet1')
row_max = ws1.max_row

# creating xml tree structure
root = etree.Element('Hierarchy')

# iterating through the xls and creating children based on the condition
for row_values in range(2, row_max+1):
parent = etree.SubElement(root, 'parent')
parent.text = ws1.cell(column=1, row=row_values).value
root.append(parent)
if (ws1.cell(column=1, row = row_values).value == ws1.cell(column=2, row = row_values-1).value):
print("------Inside if condition")
print(ws1.cell(column=2, row=row_values).value)
child = etree.SubElement(parent, 'child')
child.text = ws1.cell(column=2, row=row_values).value
parent.append(child)
print("-------Inside if condition")
tree = etree.ElementTree(root)

tree.write('C:\GSH\gsh.xml')

我得到这样的 XML..

enter image description here

但是,我的 XML 应该如下所示。

enter image description here

请提出任何建议。

enter image description here

以上是我正在处理的 XLS 源代码。

最佳答案

您可以设置变量名称而不是父项和子项。该代码只是您列表的一部分,看起来很棘手,但工作正常。 d[child[i]].text = "" 仅显示标签两侧。要使 var 与字典循环,请引用 this .

import xml.etree.ElementTree as ET

India = ET.Element('India') # set root
parent = ['India', 'Telangana', 'Telangana', 'Telangana','Nalgonda'] # parent list
child = ['Telangana', 'Cyberabad', 'Warangal','Nalgonda','BusStation'] # child list

d = {} # use dictionary to define var in loop
d['India'] = India

for i in range(len(child)):

for k, v in d.items():
if k == parent[i]:
pa = v
break

d[child[i]] = ET.SubElement(pa, child[i])
d[child[i]].text = " " # to get both side of tags

tree = ET.ElementTree(India)
tree.write('gsh.xml')

# <India>
# <Telangana>
# <Cyberabad> </Cyberabad>
# <Warangal> </Warangal>
# <Nalgonda>
# <BusStation> </BusStation>
# </Nalgonda>
# </Telangana>
# </India>

关于python - 从 Excel 创建动态嵌套 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59598406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com