Как я могу сохранить пробелы в Python 2.7 lxml? - PullRequest
0 голосов
/ 04 октября 2018

У меня огромный 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)
...