lxml没有漂亮地打印新添加的节点



我使用Python脚本在XML文件中添加节点(或复制现有节点)。脚本使用lxml库。下面是现有的代码片段:

<entitlements>
    <bpuiEnabledForSubusers>true</bpuiEnabledForSubusers>
    <appCodesAllowedForSubusers>My Accounts,Bill Pay</appCodesAllowedForSubusers>
    <enabled>true</enabled>
    <monitored>true</monitored>
</entitlements>

所以我使用lxml在权利节点中复制一个节点。然后,当我

return etree.tostring(self.root,encoding='unicode', pretty_print=True)

我得到以下xml:

<entitlements>
    <bpuiEnabledForSubusers>true</bpuiEnabledForSubusers>
    <appCodesAllowedForSubusers>My Accounts,Bill Pay</appCodesAllowedForSubusers>
    <enabled>true</enabled>
    <monitored>true</monitored>
<appCodesAllowedForSubusersCopy>My Accounts,Bill Pay</appCodesAllowedForSubusersCopy></entitlements>

因此,节点被正确地复制并添加到子节点的末尾,但是在XML中,它没有缩进到其兄弟节点的级别,并且父节点的结束标记在同一行,尽管我使用了pretty_print选项。虽然生成的XML在技术上是正确的,但根据我们现有的标准,它"看起来并不好"。

知道为什么会这样吗?

谢谢…

pretty_print=True仅在树的节点上没有尾随空格时才有有用的效果。因此,您不仅要查看如何发出它们,还要首先查看如何解析它们。

使用remove_blank_text=True分析器选项:

parser = etree.XMLParser(remove_blank_text=True)

最新更新