【问题标题】:including additional static xml with python包括带有 python 的附加静态 xml
【发布时间】:2012-01-30 06:28:39
【问题描述】:

我需要我当前的脚本来包含额外的 xml。这是当前形式的脚本:

import csv
import sys

from xml.etree import ElementTree
from xml.dom import minidom

video_data = ((256, 336000),
              (512, 592000),
              (768, 848000),
              (1128, 1208000))

with open(sys.argv[1], 'rU') as f:
    reader = csv.DictReader(f)
    for row in reader:
        switch_tag = ElementTree.Element('switch')

        for suffix, bitrate in video_data:
            attrs = {'src': ("mp4:soundcheck/{year}/{id}/{file_root_name}_{suffix}.mp4"
                             .format(suffix=str(suffix), **row)),
                     'system-bitrate': str(bitrate),
                     }
            ElementTree.SubElement(switch_tag, 'video', attrs)
        print minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml()

它当前输出这个 xml:

    <?xml version="1.0" ?>
   <switch>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_256.mp4" system-bitrate="336000"/>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_512.mp4" system-bitrate="592000"/>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_768.mp4" system-bitrate="848000"/>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_1128.mp4" system-bitrate="1208000"/>
    </switch>

我需要在 xml 文件的页眉和页脚中包含其他信息。请参见下面的示例:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd">
<smil xmlns="http://www.w3.org/2001/SMIL20/Language">
  <head>
    <meta base="rtmp://cp23636.edgefcs.net/ondemand" />
  </head>
  <body>
    <switch>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_256.mp4" system-bitrate="336000"/>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_512.mp4" system-bitrate="592000"/>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_768.mp4" system-bitrate="848000"/>
      <video src="mp4:soundcheck/2006/clay_aiken/02_sc_ca_sorry_1128.mp4" system-bitrate="1208000"/>
    </switch>
  </body>
</smil>

如何更新我当前的脚本以包含此静态信息以及从脚本当前表单中的 csv 中提取的变量?

【问题讨论】:

    标签: python xml


    【解决方案1】:

    你为什么不替换

     print minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml()
    

    与

     print header + ElementTree.tostring(switch_tag) + footer
    

    header 和 footer 分别是第二个示例输出中 switch 标记上方和下方的内容。或者,如果您想使用 prettyxml(),请从其输出中删除第一行。

     '\n'.join(minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml().splitlines()[1:])
    

    【讨论】:

    • 这正是我想要做的,但我不知道如何使页眉和页脚以正确的间距等于多行。
    • 仍有问题,但这确实有帮助。谢谢@ninjarabbit。
    • 啊,分割线后需要加入。已编辑。希望你能明白。
    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多