【问题标题】:Python XML file creation usnig a loop and assignig values to subelements使用循环创建 Python XML 文件并将值分配给子元素
【发布时间】:2020-02-04 10:41:39
【问题描述】:

我在 Python 3.6 中使用 xml.etree.ElementTree 模块来创建一个包含数十个子元素的 XML 文件。我的目标应该是这样的:

<shots>
    <shot id="0">
    <Audio_Channels>2</Audio_Channels>
    <Audio_File>testhq12.mov</Audio_File>
    <Audio_Fps>Unspecified</Audio_Fps>
    ...
    <Type>C</Type>
    <Width>4096</Width>
    <shot/>
    <shot id="1">
    ....
</shots>

到目前为止,我一直在使用以下代码来创建这个结构,但是当有很多“子字段”要添加时,它会变得非常难看

_audio_channels = Element('Audio_Channels')
shot.append(_audio_channels)
_audio_channels.text = str(audio_channels_data)

_audio_file = Element('Audio_File')
shot.append(_audio_file)
_audio_file.text = str(audio_file_data)
.
.
.

所以我尝试用一​​个看起来像这样的循环来简化它:

fields = ['Audio_Channels', 'Audio_File', 'Audio_Fps', ...]
for k in fields:
    prop = Element(k)
    shot.append(prop)

但是我不知道以后如何仅使用字段列表中的元素作为键来为他们分配任何文本? 试过了,还是不行

shot.insert(str(audio_file_data), 'Audio_File')

【问题讨论】:

  • 你能提供audio_channels_dataaudio_file_data和(我假设)audio_fps_data看起来像什么的简短例子吗?
  • 按以下顺序:2、“testhq12.mov”、“未指定”。所以一个 int, string, string
  • 基本上我不知道在“for k in fields”循环完成后使用什么方法来分配上面的值

标签: python xml assign


【解决方案1】:

如果我正确理解您的需求,请尝试以下操作:

import xml.etree.ElementTree as ET
fields = ['Audio_Channels', 'Audio_File', 'Audio_Fps']
dats = [ 2,'testhq12.mov', 'Unspecified']

shots = ET.Element('shots')
shot = ET.SubElement(shots, 'shot')
for f, d in zip(fields,dats):
    elem = ET.Element(f)
    elem.text=str(d)
    shot.append(elem)

输出应该类似于:

<shots>
   <shot>
      <Audio_Channels>2</Audio_Channels>
      <Audio_File>testhq12.mov</Audio_File>
      <Audio_Fps>Unspecified</Audio_Fps>
   </shot>
</shots>

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多