lxml(etree)-根标记的Pretty Print属性

时间:2018-11-14 15:33:11

标签: python lxml pretty-print

在python中是否可以漂亮地打印根的属性?

我使用etree扩展了子标记的属性,然后用新内容覆盖了现有文件。但是,在XML的第一代中,我们使用了一个模板,其中根标记的属性每行列出一个,而现在使用etree我无法实现相同的结果。

我发现了类似的问题,但是它们都指的是etree的教程,我发现它不完整。

希望有人使用etree找到了解决方案。

编辑:这是针对自定义XML的,因此HTML Tidy(在注释中提出)对此不起作用。

谢谢!

generated_descriptors = list_generated_files(generated_descriptors_folder)
counter = 0
for g in generated_descriptors:
    if counter % 20 == 0:
        print "Extending Descriptor # %s out of %s" % (counter, len(descriptor_attributes))

    with open(generated_descriptors_folder + "\\" + g, 'r+b') as descriptor:
        root = etree.XML(descriptor.read(), parser=parser)

        # Go through every ContextObject to check if the block is mandatory
        for context_object in root.findall('ContextObject'):
            for attribs in descriptor_attributes:
                if attribs['descriptor_name'] == g[:-11] and context_object.attrib['name'] in attribs['attributes']['mandatoryobjects']:
                    context_object.set('allow-null', 'false')
                elif attribs['descriptor_name'] == g[:-11] and context_object.attrib['name'] not in attribs['attributes']['mandatoryobjects']:
                    context_object.set('allow-null', 'true')

        # Sort the ContextObjects based on allow-null and their name
        context_objects = root.findall('ContextObject')
        context_objects_sorted = sorted(context_objects, key=lambda c: (c.attrib['allow-null'], c.attrib['name']))

        root[:] = context_objects_sorted

        # Remove mandatoryobjects from Descriptor attributes and pretty print
        root.attrib.pop("mandatoryobjects", None)
        # paste new line here


        # Convert to string in order to write the enhanced descriptor
        xml = etree.tostring(root, pretty_print=True, encoding="UTF-8", xml_declaration=True)

        # Write the enhanced descriptor
        descriptor.seek(0)  # Set cursor at beginning of the file
        descriptor.truncate(0)  # Make sure that file is empty
        descriptor.write(xml)

        descriptor.close()

    counter+=1

0 个答案:

没有答案