Python ElementTree Namespaces



Env: Python 2.7 Windows 8.1


Sample XML:



<?xml version="1.0" encoding="UTF-8"?>
<edmx:Edmx xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx" Version="1.0">
<edmx:DataServices xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:MaxDataServiceVersion="3.0" m:DataServiceVersion="3.0">
<Schema xmlns="http://ift.tt/1cMNgQg" Namespace="DataModel">
<EntityContainer Name="EC1" xmlns:p6="http://ift.tt/1hzy3ZA" p6:LazyLoadingEnabled="true" m:IsDefaultEntityContainer="true">
<EntitySet Name="Attributes" EntityType="Model.Attribute"/>
<EntitySet Name="AttributeControlTypes" EntityType="Model.AttributeControlType"/>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>


test code:



import xml.etree.ElementTree as ET
from cStringIO import StringIO

def parse(self):
events = ("end", "start-ns", "end-ns", "start")
namespaces = []
for event, elem in ET.iterparse(StringIO(self.document), events=events):
if event == "start-ns":
print "startns: {}".format(elem)
namespaces.append(elem)
elif event == "end-ns":
removed = namespaces.pop()
print "removedns: {}".format(removed)
elif event == "start":
print elem.tag


My understanding is if a tag has a namespace attached to it then all the child elements should also be in the same namespace. When I try to parse the above XML I would have expected the "entitySet" elements to be in the namespace defined in "EntityContainer":


output:



startns: (u'edmx', 'http://ift.tt/1cMNdUC')
{http://ift.tt/1u8iUlx
startns: (u'm', 'http://ift.tt/1dtZymv')
{http://ift.tt/1u8iUC2
startns: ('', 'http://ift.tt/1cMNgQg')
{http://ift.tt/1u8iThi
startns: (u'p6', 'http://ift.tt/1hzy3ZA')
{http://ift.tt/1meEyW6
{http://ift.tt/1meEypi
{http://ift.tt/1meEypi
removedns: (u'p6', 'http://ift.tt/1hzy3ZA')
removedns: ('', 'http://ift.tt/1cMNgQg')
removedns: (u'm', 'http://ift.tt/1dtZymv')
removedns: (u'edmx', 'http://ift.tt/1cMNdUC')


ElementTree sees the start of the namespace(p6) but seems to add the "EntityContainer" child elements into the namespace of the "Schema" element. Is this working as expected?


No comments:

Post a Comment