Python: Update XML-file using ElementTree while conserving layout as much as possible

后端 未结 4 968
天命终不由人
天命终不由人 2021-01-04 03:36

I have a document which uses an XML namespace for which I want to increase /group/house/dogs by one: (the file is called houses.xml)



        
4条回答
  •  孤街浪徒
    2021-01-04 04:16

    Round-tripping, unfortunately, isn't a trivial problem. With XML, it's generally not possible to preserve the original document unless you use a special parser (like DecentXML but that's for Java).

    Depending on your needs, you have the following options:

    • If you control the source and you can secure your code with unit tests, you can write your own, simple parser. This parser doesn't accept XML but only a limited subset. You can, for example, read the whole document as a string and then use Python's string operations to locate and replace anything up to the next <. Hack? Yes.

    • You can filter the output. XML allows the string only in one place, so you can search&replace it with < and then the same with . This is pretty safe unless you can have CDATA in your XML.

    • You can write your own, simple XML parser. Read the input as a string and then create Elements for each pair of <> plus their positions in the input. That allows you to take the input apart quickly but only works for small inputs.

提交回复
热议问题