python xml基于子元素文本打印特定的子节点 [英] python xml print particular child node based on sub-element text

查看:129
本文介绍了python xml基于子元素文本打印特定的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例XML,如下所示:

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>

在这里我想遍历孩子以了解 MgmtAppType 的值是 TL1 ,如果要打印所有与之关联的元素,即MoID,AccountName,ProtocolType,MgmtAppType,AuthenticationType。
我尝试使用以下代码,但是只打印 MgmtAppType

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?

推荐答案

搜索命名空间XML示例的更好方法是使用自己的前缀创建字典并使用搜索功能中的那些:

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

这篇关于python xml基于子元素文本打印特定的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆