Suppose I have an XML string:
thing
stuff
and I want to insert a namespace of the type used by XML Schema, putting a prefix in front of all the element names.
thing
stuff
Is there a way to do this (aside from brute-force find-replace or regex) using lxml.etree or a similar library?
解决方案
I don't think this can be done with just ElementTree.
Manipulating namespaces is sometimes surprisingly tricky. There are many questions about it here on SO. Even with the more advanced lxml library, it can be really hard. See these related questions:
Below is a solution that uses XSLT.
Code:
from lxml import etree
XML = '''
thing
stuff
'''
XSLT = '''
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="www.example.com">
'''xml_doc = etree.fromstring(XML)
xslt_doc = etree.fromstring(XSLT)
transform = etree.XSLT(xslt_doc)
print transform(xml_doc)
Output:
thing
stuff