On 14/06/25 20:33, Schimon Jehudah via lxml - The Python XML Toolkit wrote:> Would it be sensible to allow a negative value:

e_feed.insert(-1, xslt_reference)

If you test this, you will find out that inserting at negative indexes is already a valid operation: `insert(-x, el)` inserts at index `x` *from the end*.

This is the normal behaviour of indexing in Python.

And if you were using lxml, which you are not (lxml and xml.etree are different packages), what you request would already work if you used the `addprevious` method:

>>> e_feed = ET.Element("feed")
>>> e_feed.set("xmlns", "http://www.w3.org/2005/Atom";)
>>> xslt_reference = ET.ProcessingInstruction(
...     "xml-stylesheet",
...     "type=\"text/xml\" href=\"stylesheet.xsl\"")
>>>
>>> ET.tostring(ET.ElementTree(e_feed))
b'<feed xmlns="http://www.w3.org/2005/Atom"/>'
>>> e_feed.addprevious(xslt_reference)
>>> ET.tostring(ET.ElementTree(e_feed))
b'<?xml-stylesheet type="text/xml" href="stylesheet.xsl"?><feed xmlns="http://www.w3.org/2005/Atom"/>'

The way you namespace the element is also very much a serialization hack, you should create the element using a QName tag or Clark's Notation. You can use `register_namespace` to force the namespace prefix if you care:

>>> doc1 = ET.Element('{foo}bar')
>>> doc2 = ET.Element(ET.QName('foo', 'bar'))
>>> ET.tostring(doc1), ET.tostring(doc2)
(b'<ns0:bar xmlns:ns0="foo" />', b'<ns0:bar xmlns:ns0="foo" />')
>>> ET.register_namespace('', 'foo')
>>> ET.tostring(doc1), ET.tostring(doc2)
(b'<bar xmlns="foo" />', b'<bar xmlns="foo" />')

in lxml you can also use the nsmap feature:

>>> etree.tostring(etree.Element('{foo}bar', nsmap={None: 'foo'}))
b'<bar xmlns="foo"/>'
_______________________________________________
lxml - The Python XML Toolkit mailing list -- lxml@python.org
To unsubscribe send an email to lxml-le...@python.org
https://mail.python.org/mailman3//lists/lxml.python.org
Member address: arch...@mail-archive.com

Reply via email to