解析 xml 文件的脚本删除了第一行

Script to parse xml files removes first line

解析 xml 文件的脚本删除了第一行 这是 python 脚本,我必须对多个 .xml 文件的 uuid 进行排序:

import os
import lxml.etree as ET

inputpath = 
xsltfile = 
outpath = 

dir = []

for dirpath, dirnames, filenames in os.walk(inputpath):
    structure = os.path.join(outpath, dirpath[len(inputpath):])
    if not os.path.isdir(structure):
        os.mkdir(structure)
    for filename in filenames:
        if filename.endswith(('.xml')):
            dir = os.path.join(dirpath, filename)
            print(dir)
            dom = ET.parse(dir)
            xslt = ET.parse(xsltfile)
            transform = ET.XSLT(xslt)
            newdom = transform(dom)
            outfile = open(structure + "\" + filename, 'a')
            outfile.write(ET.tostring(newdom,pretty_print=True).decode())

这是我针对多个 .xml 文件使用的 .xslt 模板

第一行叫做XML声明,默认情况下etree.tostring()不输出,需要加上xml_declaration=True参数,见lxml docs.