如何使用python 2.7 lxml保留空格?

时间:2018-10-04 11:34:50

标签: python lxml

我有一个巨大的xml文件(数千行),我需要更改一些属性参数。
Xml看起来像这样:

<person id="name" name="pers_name">
    <group id="Common">
        <emotion id="smile">
            <texture texture="smile" x="-131" y="-17" />
            <effect name="name1" x="51" y="438" />
            <effect name="name2" x="61" y="419" />
            <effect name="name3" x="55" y="312" />
        </emotion>
     </group>
 </person>

这样做并用tree.write(path, encoding='utf-8', xml_declaration=True)编写后,在关闭标签之前我失去了空格。
我该如何保存?

<person id="name" name="pers_name">
    <group id="Common">
        <emotion id="smile">
            <texture texture="smile" x="-131" y="-17"/>
            <effect name="name1" x="51" y="438"/>
            <effect name="name2" x="61" y="419"/>
            <effect name="name3" x="55" y="312"/>
        </emotion>
     </group>
 </person>

代码

from lxml import etree

# Offsets
x_offset = -10
y_offset = -20

tree = etree.parse(path)
XML = tree.getroot()

for effect in XML.iter('effect'):
    texture_offset_x = int(effect.get('texture_offset_x')) + x_offset
    texture_offset_y = int(effect.get('texture_offset_y')) + y_offset
    effect.set('texture_offset_x', str(texture_offset_x))
    effect.set('texture_offset_y', str(texture_offset_y))

tree.write(path, encoding='utf-8', xml_declaration=True)

0 个答案:

没有答案