擅长:python、mysql、java
<p>{a2是一个名称空间的组合,显示了如何修改^的名称空间。在</p>
<p>代码有点粗糙(我特别怀疑使用<code>_setroot</code>方法是否符合犹太教规),但它似乎有效:</p>
<pre><code>from lxml import etree
inputfile = 'data.xml'
target_ns = 'urn:ietf:params:xml:ns:epp-1.0'
nsmap = {None: target_ns}
tree = etree.parse(inputfile)
root = tree.getroot()
# here we set the namespace of all elements to target_ns
for elem in root.getiterator():
tag = etree.QName(elem.tag)
elem.tag = '{%s}%s' % (target_ns, tag.localname)
# create a new root element and set the namespace map, then
# copy over all the child elements
new_root = etree.Element(root.tag, nsmap=nsmap)
new_root[:] = root[:]
# create a new elementtree with new_root so that we can use the
# .write method.
tree = etree.ElementTree()
tree._setroot(new_root)
tree.write('done.xml',
pretty_print=True, xml_declaration=True, encoding='UTF-8')
</code></pre>
<p>给定示例输入,将在<code>done.xml</code>中生成:</p>
^{pr2}$