Python: namespaces in xml ElementTree (or lxml)

前端 未结 2 817
无人及你
无人及你 2021-01-17 23:05

I want to retrieve a legacy xml file, manipulate and save it.

Here is my code:

from xml.etree import cElementTree as ET
NS = \"{http://www.somedomain         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 23:24

    Have a look at the lxml tutorial section on namespaces. Also this article about namespaces in ElementTree.

    Problem 1: Put up with it, like everybody else does. Instead of "%(ns)Event" % {'ns':NS } try NS+"Event".

    Problem 2: By default, the XML declaration is written only if it is required. You can force it (lxml only) by using xml_declaration=True in your write() call.

    Problem 3: The nsmap arg appears to be lxml-only. AFAICT it needs a MAPping, not a string. Try nsmap={None: NS}. The effbot article has a section describing a workaround for this.

提交回复
热议问题