[Tutor] XML parsing
Peter Otten
__peter__ at web.de
Thu Mar 29 03:56:08 EDT 2018
Asif Iqbal wrote:
> I am trying to extract all the *template-name*s, but no success yet
>
> Here is a sample xml file
>
> <collection xmlns:y="http://tail-f.com/ns/rest">
> <template-metadata xmlns="http://networks.com/nms">
> <template-name>ALLFLEX-BLOOMINGTON</template-name>
> <type>post-staging</type>
> <device-type>full-mesh</device-type>
> <provider-tenant>ALLFLEX</provider-tenant>
> <subscription xmlns="http://networks.com/nms">
> <solution-tier>advanced-plus</solution-tier>
> <bandwidth>1000</bandwidth>
> <is-analytics-enabled>true</is-analytics-enabled>
> <is-primary>true</is-primary>
> </subscription>
> ....
> </collection>
>
> with open('/tmp/template-metadata') as f:
> import xml.etree.ElementTree as ET
> root = ET.fromstring(f.read())
>
> print len(root)
> print root[0][0].text
> for l in root.findall('template-metadata'):
> print l
>
>
> 392
> ALLFLEX-BLOOMINGTON
>
>
> It prints the length of the tree and the first element of the first child,
> but when I try to loop through to find all the 'template-name's
> it does not print anything.
>
> What am I doing wrong?
You have to include the namespace:
for l in root.findall('{http://networks.com/nms}template-metadata'):
...
More information about the Tutor
mailing list