如何将xml树放入单独的python文件中?

问题描述 投票:0回答:1

我使用 python 和 xml.etree.ElementTree 来构建 xml 文件。但只有基础树有超过 350 行,我想将其放在一个单独的文件中。我该怎么做?

我的代码:

import xml.etree.ElementTree as ET

***
mydata = ET.Element('root_data')
version = ET.SubElement(root_data, 'version')
date = ET.SubElement(root_data, 'date')
groups = ET.SubElement(root_data, 'groups')
group = ET.SubElement(groups, 'group')
templates = ET.SubElement(root_data, 'templates')
template = ET.SubElement(templates, 'template')
tpl_linked = ET.SubElement(template, 'template')
--- a lot more lines like this ---
***

所以我想将 *** 之间的内容放在一个单独的文件中。

我尝试通过函数调用它,但这不起作用,因为主程序中不知道变量。

python xml elementtree
1个回答
1
投票

xml.etree.ElementTree
可以直接写入文件,参见doc

import xml.etree.ElementTree as ET

root_data = ET.Element('root_data') # corrected your code here
version = ET.SubElement(root_data, 'version')
date = ET.SubElement(root_data, 'date')
groups = ET.SubElement(root_data, 'groups')
group = ET.SubElement(groups, 'group')
templates = ET.SubElement(root_data, 'templates')
template = ET.SubElement(templates, 'template')
tpl_linked = ET.SubElement(template, 'template')

# For better format
ET.indent(root_data, space='  ')
ET.dump(root_data)

# Write the tree to file
tree = ET.ElementTree(root_data)
tree.write('output_file.xml', encoding='utf-8', xml_declaration=True)
© www.soinside.com 2019 - 2024. All rights reserved.