在lxml中无法修改节点的名称空间映射。请将此开放票证将此功能作为愿望清单项目。
它起源于lxml邮件列表上的该线程,其中提供了一种替代方法来替换根节点。但是,替换根节点存在一些问题:请参见上面的票证。
为了完整性,我将建议的根替换解决方法代码放在此处:
>>> DOC = """<sbml xmlns="http://www.sbml.org/sbml/level2/version4" xmlns:celldesigner="http://www.sbml.org/2001/ns/celldesigner" level="2" version="4">... <model metaid="untitled" id="untitled">... <annotation>...</annotation>... <listOfUnitDefinitions>...</listOfUnitDefinitions>... <listOfCompartments>...</listOfCompartments>... <listOfSpecies>... <species metaid="s1" id="s1" name="GenA" compartment="default" initialAmount="0">... <annotation>...<celldesigner:extension>...</celldesigner:extension>... </annotation>... </species>... <species metaid="s2" id="s2" name="s2" compartment="default" initialAmount="0">... <annotation>... <celldesigner:extension>...</celldesigner:extension>... </annotation>... </species>... </listOfSpecies>... <listOfReactions>...</listOfReactions>... </model>... </sbml>""">>> >>> from lxml import etree>>> from StringIO import StringIO>>> NS = "http://this.is.some/custom_namespace">>> tree = etree.ElementTree(element=None, file=StringIO(DOC))>>> root = tree.getroot()>>> nsmap = root.nsmap>>> nsmap['kjw'] = NS>>> new_root = etree.Element(root.tag, nsmap=nsmap)>>> new_root[:] = root[:]>>> new_root.append(etree.Element('{%s}%s' % (NS, 'test')))>>> new_root.append(etree.Element('{%s}%s' % (NS, 'test')))>>> print etree.tostring(new_root, pretty_print=True)<sbml xmlns:celldesigner="http://www.sbml.org/2001/ns/celldesigner" xmlns:kjw="http://this.is.some/custom_namespace" xmlns="http://www.sbml.org/sbml/level2/version4"><model metaid="untitled" id="untitled"> <annotation>...</annotation> <listOfUnitDefinitions>...</listOfUnitDefinitions> <listOfCompartments>...</listOfCompartments> <listOfSpecies> <species metaid="s1" id="s1" name="GenA" compartment="default" initialAmount="0"> <annotation> <celldesigner:extension>...</celldesigner:extension> </annotation> </species> <species metaid="s2" id="s2" name="s2" compartment="default" initialAmount="0"> <annotation><celldesigner:extension>...</celldesigner:extension> </annotation> </species> </listOfSpecies> <listOfReactions>...</listOfReactions> </model><kjw:test/><kjw:test/></sbml>


