[lxml-dev] Proper syntax to insert elements with namespaces?
Stefan Behnel
stefan_ml at behnel.de
Wed Jul 9 09:17:49 CEST 2008
Hi,
Mike MacCana wrote:
> I'm reading some OpenDocument files with lxml, and inserting various
> elements. A snippet, which works fine, is below. Yay LXML!
:)
> ## Parse our content as 'document'
> document = etree.parse(contentfile)
> print etree.tostring(document.getroot(), pretty_print=True),
>
> ## The body of the document, where we'll add our text elements
> body = document.xpath('/office:document-content/office:body/office:text', namespaces={'office':'urn:oasis:names:tc:opendocument:xmlns:office:1.0','text':'urn:oasis:names:tc:opendocument:xmlns:text:1.0'})
>
> ## Insert some text as element one
> print "adding element:"
> body[0].insert(1, etree.Element("text",name="Standard"))
>
> ## Identify the element by it's xpath and change its contents.
> newelement = document.xpath('/office:document-content/office:body/office:text/text', namespaces={'office':'urn:oasis:names:tc:opendocument:xmlns:office:1.0','text':'urn:oasis:names:tc:opendocument:xmlns:text:1.0'})
> newelement[0].text="new element text"
>
>
> 1. Is there a better way to refer to, and set the text of, the newly
> created element?
You mean like
text_element = etree.Element("text",name="Standard")
text_element.text = "new text"
body[0].insert(1, text_element)
although I'd prefer doing
text_element = body.makeelement("text",name="Standard")
...
because it's faster and a bit more memory friendly (no need to create a new
document for the element).
> 2. How do I insert an element with a namespace? The code above creates:
> <text name="Standard">new element text</text>
>
> But I'd prefer:
> <text:p text:style-name="Standard">old element</text:p>
http://codespeak.net/lxml/tutorial.html#namespaces
Stefan
More information about the lxml-dev
mailing list