Modify XML with Python

Viewed 42

I have an XML file which I want to modify and save to futher use. I only want to change text of some elements, but when I do, it also deletes all the line breaks in element's attributes:

<smth.xml
    attr1="name1"
    attr2="name2"
    smth="21315423"
    Debug="false" >

becomes

<smth.xml attr1="name1" attr2="name2" smth="21315423" Debug="false">

I am currently using lxml lib with parser = etree.XMLParser(encoding='utf-8')

1 Answers

but when I do, it also deletes all the line breaks in element's attributes

That's normal. Line-breaks between attributes in the XML source code are not part of the XML data model.

You are allowed to type them when you edit an XML file by hand, but XML parsers are not required by the spec to pay any attention to them, because they carry no meaning. So practically no XML parser does (I don't know a single XML parser that does).

I can only recommend one thing: Get over it. Don't try to retain them, that's fruitless, pointless, and it won't work.

Load the XML, read data from it, modify it, save it. Don't get too worked up about irrelevant details.

Related