toprettyxml()在Python中向DOCTYPE添加新行

toprettyxml()在Python中向DOCTYPE添加新行,python,xml,pretty-print,elementtree,minidom,Python,Xml,Pretty Print,Elementtree,Minidom,使用prettify时,我的DOCTYPE被分成三行。我怎样才能把它保持在一条线上 “中断”输出: 剧本: 导入csv 导入系统 导入操作系统路径 从xml.etree导入元素树 从xml.etree.ElementTree导入元素、子元素、注释到字符串 从xml.dom导入minidom def美化(doctype,elem): “”“为元素返回打印精美的XML字符串。 """ rough_string=doctype+ElementTree.tostring(元素'utf-8') 重解析

使用
prettify
时,我的DOCTYPE被分成三行。我怎样才能把它保持在一条线上

“中断”输出:


剧本:

导入csv
导入系统
导入操作系统路径
从xml.etree导入元素树
从xml.etree.ElementTree导入元素、子元素、注释到字符串
从xml.dom导入minidom
def美化(doctype,elem):
“”“为元素返回打印精美的XML字符串。
"""
rough_string=doctype+ElementTree.tostring(元素'utf-8')
重解析=minidom.parseString(粗字符串)
返回重新解析的.toprettyxml(indent=,encoding='utf-8')
doctype=“”
视频数据=((256,336000),
(512, 592000),
(768, 848000),
(1128, 1208000))
将open(sys.argv[1],'rU')作为f:
reader=csv.DictReader(f)
对于读取器中的行:
根=元素('smil')
root.set('xmlns','http://www.w3.org/2001/SMIL20/Language')
head=子元素(根,“head”)
元=子元素(头,'元基='rtmp://cp23636.edgefcs.net/ondemand"')
body=子元素(根“body”)
switch_tag=ElementTree.SubElement(主体“switch”)
对于后缀,视频数据中的比特率:
attrs={'src':(“mp4:soundcheck/{year}/{id}/{file_root_name}{suffix}.mp4”
.format(后缀=str(后缀),**行)),
“系统比特率”:str(比特率),
}
ElementTree.SubElement(开关标签'video',attrs)
file\u root\u name=行[“file\u root\u name”]
年=行[“年”]
id=行[“id”]
路径=年份+'-'+id
file_name=行['file_root_name']+'.smil'
完整路径=os.path.join(路径、文件名)
输出=打开(完整路径“w”)
output.write(美化(doctype,root))

我认为您至少有三种选择:

  • 接受这些新词就行了。他们可能是不受欢迎的和丑陋的,但他们是完全合法的

  • 添加一个用更好的DOCTYPE替换坏DOCTYPE的乱码。也许是这样的:

    重新导入
    pretty_xml=prettify(doctype,elem)
    
    m=re.search(“(我认为不可能删除
    Node.toprettyxml
    DOCTYPE
    生成的换行符,至少是以Pythonic的方式

    它是
    DocumentType
    类的
    writexml
    方法,该方法从的第1284行开始,插入有问题的换行符。插入的换行符字符串最初来自
    节点.toprettyxml
    方法,并通过
    Document
    类的
    writexml
    方法传递。相同的newline字符串还被传递给
    节点
    的各种其他子类的
    writexml
    方法。在调用
    节点时更改换行符字符串。prettyxml
    将更改整个输出XML中使用的换行符字符串

    围绕这一点有各种各样的方法:修改
    minidom
    模块的本地副本,'monkey patch'是
    DocumentType
    类的
    writexml
    方法,或者对XML字符串进行后期处理以删除不需要的换行符。但是,这些方法都不吸引我


    对我来说,最好的方法似乎是保持现状。将
    DOCTYPE
    拆分为多行是否真的是一个严重的问题?

    查看了您当前的脚本以及您在这个主题上提出的其他问题后,我想您可以通过使用字符串ma构建smil文件来简化您的生活人口

    您的文件中几乎所有的xml都是静态的。您需要担心的唯一数据是
    video
    标记的属性值。为此,标准库中有一个方便的函数,可以完全满足您的需要:

    因此,考虑到这些要点,这里有一个脚本应该更容易使用:

    import sys, os, csv
    from xml.sax.saxutils import quoteattr
    
    smil_header = '''\
    <?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>
    '''
    smil_video = '''\
          <video src=%s system-bitrate=%s/>
    '''
    smil_footer = '''\
        </switch>
      </body>
    </smil>
    '''
    
    src_format = 'mp4:soundcheck/%(year)s/%(id)s/%(file_root_name)s_%(suffix)s.mp4'
    
    video_data = (
        ('256', '336000'), ('512', '592000'),
        ('768', '848000'), ('1128', '1208000'),
        )
    
    root = os.getcwd()
    if len(sys.argv) > 2:
        root = sys.argv[2]
    
    with open(sys.argv[1], 'rU') as stream:
    
        for row in csv.DictReader(stream):
            smil = [smil_header]
            for suffix, bitrate in video_data:
                row['suffix'] = suffix
                smil.append(smil_video % (
                    quoteattr(src_format) % row, quoteattr(bitrate)
                    ))
            smil.append(smil_footer)
    
            directory = os.path.join(root, '%(year)s-%(id)s' % row)
            try:
                os.makedirs(directory)
            except OSError:
                pass
            path = os.path.join(directory, '%(file_root_name)s.smil' % row)
            print ':: writing file:', path
            with open(path, 'wb') as stream:
                stream.write(''.join(smil))
    
    导入系统、操作系统、csv
    从xml.sax.saxutils导入quoteattr
    smil_头=“”\
    '''
    smil_视频=“”\
    '''
    smil_页脚=“”\
    '''
    src_format='mp4:soundcheck/%(year)s/%(id)s/%(file_root_name)s_u%(后缀)s.mp4'
    视频数据=(
    ('256', '336000'), ('512', '592000'),
    ('768', '848000'), ('1128', '1208000'),
    )
    root=os.getcwd()
    如果len(sys.argv)>2:
    root=sys.argv[2]
    以open(sys.argv[1],“rU”)作为流:
    对于csv.DictReader(流)中的行:
    smil=[smil\U头文件]
    对于后缀,视频数据中的比特率:
    行['suffix']=后缀
    smil.append(smil\u视频%(
    quoteattr(src_格式)%行,quoteattr(比特率)
    ))
    smil.append(smil\u页脚)
    directory=os.path.join(根,,%(年)s-%(id)s'%row)
    尝试:
    os.makedirs(目录)
    除操作错误外:
    通过
    path=os.path.join(目录,,%(文件根目录名称)s.smil“%row”)
    打印“::写入文件:”,路径
    以open(路径“wb”)作为流:
    stream.write(“”.join(smil))
    
    <?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/1/clay_aiken/02_sc_ca_sorry_256.mp4" system-bitrate="336000"/>
          <video src="mp4:soundcheck/1/clay_aiken/02_sc_ca_sorry_512.mp4" system-bitrate="592000"/>
          <video src="mp4:soundcheck/1/clay_aiken/02_sc_ca_sorry_768.mp4" system-bitrate="848000"/>
          <video src="mp4:soundcheck/1/clay_aiken/02_sc_ca_sorry_1128.mp4" system-bitrate="1208000"/>
        </switch>
      </body>
    </smil>
    
    import sys, os, csv
    from xml.sax.saxutils import quoteattr
    
    smil_header = '''\
    <?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>
    '''
    smil_video = '''\
          <video src=%s system-bitrate=%s/>
    '''
    smil_footer = '''\
        </switch>
      </body>
    </smil>
    '''
    
    src_format = 'mp4:soundcheck/%(year)s/%(id)s/%(file_root_name)s_%(suffix)s.mp4'
    
    video_data = (
        ('256', '336000'), ('512', '592000'),
        ('768', '848000'), ('1128', '1208000'),
        )
    
    root = os.getcwd()
    if len(sys.argv) > 2:
        root = sys.argv[2]
    
    with open(sys.argv[1], 'rU') as stream:
    
        for row in csv.DictReader(stream):
            smil = [smil_header]
            for suffix, bitrate in video_data:
                row['suffix'] = suffix
                smil.append(smil_video % (
                    quoteattr(src_format) % row, quoteattr(bitrate)
                    ))
            smil.append(smil_footer)
    
            directory = os.path.join(root, '%(year)s-%(id)s' % row)
            try:
                os.makedirs(directory)
            except OSError:
                pass
            path = os.path.join(directory, '%(file_root_name)s.smil' % row)
            print ':: writing file:', path
            with open(path, 'wb') as stream:
                stream.write(''.join(smil))