[lxml-dev] Proper syntax to insert elements with namespaces?
Mike MacCana
mmaccana at au1.ibm.com
Wed Jul 9 08:43:41 CEST 2008
Hello all,
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?
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>
Cheers,
Mike
________________________________________________
Mike MacCana
Technical Specialist
Australia Linux and Virtualisation Services
IBM Global Services
Level 14, 60 City Rd
Southgate Vic 3000
Phone: +61-3-8656-2138
Fax: +61-3-8656-2423
Email: mmaccana at au1.ibm.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codespeak.net/pipermail/lxml-dev/attachments/20080709/9b1c6a46/attachment.htm
More information about the lxml-dev
mailing list