我可以使用 ElementTree 添加 XML 节点,但这会在一行中返回输出,而不是当我以文本格式打开 xml 文件时看起来类似的树结构。我还尝试使用 minidom.toprettyxml 但我不知道如何将输出添加到原始 XML。由于我希望脚本能够在其他环境中重现,因此我不喜欢使用 lxml 等外部库。有人可以帮助我如何漂亮地打印输出吗? - python 2.7
示例 XML。这就是它在文本格式和资源管理器中的外观。
<?xml version="1.0" encoding="utf-8"?>
<default_locators >
<locator_ref>
<name>cherry</name>
<display_name>cherrycherry</display_name>
<workspace_properties>
<factory_progid>Workspace</factory_progid>
<path>InstallDir</path>
</workspace_properties>
</locator_ref>
</default_locators>
文本格式和资源管理器的预期输出。
<?xml version="1.0" encoding="utf-8"?>
<default_locators >
<locator_ref>
<name>cherry</name>
<display_name>cherrycherry</display_name>
<workspace_properties>
<factory_progid>Workspace</factory_progid>
<path>InstallDir</path>
</workspace_properties>
</locator_ref>
<locator_ref>
<name>berry</name>
<display_name>berryberry</display_name>
<workspace_properties>
<factory_progid>Workspace</factory_progid>
<path>C:\temp\temp</path>
</workspace_properties>
</locator_ref>
</default_locators>
我的脚本
#coding: cp932
import xml.etree.ElementTree as ET
tree = ET.parse(r"C:\DefaultLocators.xml")
root = tree.getroot()
locator_ref = ET.SubElement(root, "locator_ref")
name = ET.SubElement(locator_ref, "name")
name.text = " berry"
display_name = ET.SubElement(locator_ref, "display_name")
display_name.text = "berryberry"
workspace_properties = ET.SubElement(locator_ref, "workspace_properties")
factory_progid = ET.SubElement(workspace_properties,"factory_progid")
factory_progid.text = "Workspace"
path = ET.SubElement(workspace_properties, "path")
path.text = r"c:\temp\temp"
tree.write(r"C:\DefaultLocators.xml", encoding='utf-8')
返回的输出。运行脚本后,新节点将添加到我的sample.xml 文件中,但它会在一行中返回输出,并从原始sample.xml 文件中删除所有换行符和缩进。至少当我以文本格式打开sample.xml 文件时,它看起来是这样的。但是,当我在资源管理器中打开sample.xml 文件时,它看起来很好。我仍然看到像以前一样的换行符和缩进。如何在运行脚本后仍保留原始树结构的文本格式?
<default_locators>
<locator_ref>
<name>cherry</name>
<display_name>cherrycherry</display_name>
<workspace_properties>
<factory_progid>Workspace</factory_progid>
<path>InstallDir</path>
</workspace_properties>
</locator_ref>
<locator_ref><name> berry</name><display_name>berryberry</display_name><workspace_properties><factory_progid>Workspace</factory_progid><path>c:\temp\temp</path></workspace_properties></locator_ref></default_locators>
最佳答案
处理element时,可以这样做:element.tail = '\n'
然后,它将被写成单行。
关于python - 在 python 中添加新的 XML 节点并漂亮地打印 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14228659/