2016-08-26 23 views
0

我正在使用Python脚本在XML文件中添加节点(或复制现有节点)。该脚本使用lxml库。这里是现有的片段:Python: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在技术上是正确的,但根据我们现有的标准,它并不“看起来不错”。

任何想法为什么会发生这种情况?

谢谢...

回答

1

pretty_print=True只有当你的树没有节点上尾随空白已有用的效果。因此,你不仅要看你如何排出它们,而且要看你如何解析它们。

使用remove_blank_text=True解析器选项:

parser = etree.XMLParser(remove_blank_text=True) 
+0

感谢@Charles,工作就像一个魅力! – RMittelman