@@ -597,6 +597,44 @@ def testWriteXMLAttributeNamespacePrefix(self):
597597 '<root xmlns:ns0="http://xml.python.org/ns" '
598598 'xmlns:ns1="http://xml.python.org/ns2" '
599599 'ns0:attr="value" ns1:attr2="value2"/>' )
600+ # The same namespace gets the same prefix.
601+ root .setAttributeNS ("http://xml.python.org/ns" , "attr3" , "value3" )
602+ self .assertEqual (dom .documentElement .toxml (),
603+ '<root xmlns:ns0="http://xml.python.org/ns" '
604+ 'xmlns:ns1="http://xml.python.org/ns2" '
605+ 'ns0:attr="value" ns1:attr2="value2" ns0:attr3="value3"/>' )
606+ dom .unlink ()
607+
608+ def testWriteXMLAttributeNamespacePrefixReused (self ):
609+ # A prefix already bound to the namespace of the attribute is used.
610+ dom = Document ()
611+ root = dom .appendChild (
612+ dom .createElementNS ("http://xml.python.org/ns" , "p:root" ))
613+ root .setAttributeNS ("http://xml.python.org/ns" , "attr" , "value" )
614+ self .assertEqual (dom .documentElement .toxml (),
615+ '<p:root xmlns:p="http://xml.python.org/ns" p:attr="value"/>' )
616+ # The prefix can be bound for an ancestor.
617+ child = root .appendChild (dom .createElement ("child" ))
618+ child .setAttributeNS ("http://xml.python.org/ns" , "attr" , "value" )
619+ self .assertEqual (child .toxml (), '<child p:attr="value"/>' )
620+ # The prefix bound for a preceding attribute is reused.
621+ root .setAttributeNS ("http://xml.python.org/ns3" , "q:attr3" , "value3" )
622+ root .setAttributeNS ("http://xml.python.org/ns3" , "attr4" , "value4" )
623+ self .assertEqual (dom .documentElement .toxml (),
624+ '<p:root xmlns:p="http://xml.python.org/ns" '
625+ 'xmlns:q="http://xml.python.org/ns3" '
626+ 'p:attr="value" q:attr3="value3" q:attr4="value4">'
627+ '<child p:attr="value"/></p:root>' )
628+ root .removeAttributeNS ("http://xml.python.org/ns3" , "attr3" )
629+ root .removeAttributeNS ("http://xml.python.org/ns3" , "attr4" )
630+ # The prefix must not be taken by an explicit declaration.
631+ root .setAttributeNS (xml .dom .XMLNS_NAMESPACE , "xmlns:ns0" , "other" )
632+ root .setAttributeNS ("http://xml.python.org/ns2" , "attr2" , "value2" )
633+ self .assertEqual (dom .documentElement .toxml (),
634+ '<p:root xmlns:p="http://xml.python.org/ns" '
635+ 'xmlns:ns1="http://xml.python.org/ns2" '
636+ 'p:attr="value" xmlns:ns0="other" ns1:attr2="value2">'
637+ '<child p:attr="value"/></p:root>' )
600638 dom .unlink ()
601639
602640 def testWriteXMLXMLPrefix (self ):
0 commit comments