python xml print particular child node based on su

2019-08-09 06:59发布

问题:

I have a sample XML like below:

<data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
    <sessions xmlns="com:infinera:common:session">
        <session>
            <MoId>admin_12</MoId>
            <AccountName>admin</AccountName>
            <ProtocolType>SSH</ProtocolType>
            <MgmtAppType>CLI</MgmtAppType>
            <AuthenticationType>LOCAL</AuthenticationType>
        </session>
        <session>
            <MoId>admin_13</MoId>
            <AccountName>admin</AccountName>
            <ProtocolType>TELNET</ProtocolType>
            <MgmtAppType>TL1</MgmtAppType>
            <AuthenticationType>LOCAL</AuthenticationType>
        <session>
    </sessions>
</data>

Here i want to iterate through the children to find if value of MgmtAppType is TL1 and if it is I want to print all the elements associated it i.e. MoID, AccountName, ProtocolType, MgmtAppType, AuthenticationType. I tried with below code, but this prints only the value of MgmtAppType

import xml.etree.ElementTree as ET
root = ET.parse('C:\\session.xml')
roots = root.getroot()
for sess in roots.iter():
    if (sess.tag == "{com:infinera:common:session}MgmtAppType") and (sess.text == "TL1"):
            for chd in sess.iter():
                    print chd.text

How would i print all the elements of particular child node based on the search?

回答1:

A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions:

import xml.etree.ElementTree as ET

root = ET.parse('C:\\session.xml').getroot()
ns = {'common': 'com:infinera:common:session'}
for session in root.findall('common:sessions/common:session[common:MgmtAppType="TL1"]', ns):
    print([el.text for el in list(session)])

The output (as a list of consecutive elements values):

['admin_13', 'admin', 'TELNET', 'TL1', 'LOCAL']

https://docs.python.org/3/library/xml.etree.elementtree.html#parsing-xml-with-namespaces