如何为从XML文件解析为空的元素创建Python占位符?

时间:2016-01-15 21:32:27

标签: python python-3.x xml-parsing elementtree

我想首先说我是Python的新手,但我喜欢这种语言。

问题: 我以XML格式提供了一个非常大的Juniper配置文件。我正在使用ElementTree库来解析文件。该文件有5个主要根(父)和几个嵌套子。我们试图将文本附加到几个元素标签的几个列表中并显示数据。我已经验证了每个的路径。我认为问题是某些元素是空的,所以当我显示每个列表中的数据时,相应的数据输出与XML文档中的内容不匹配。有没有办法在解析文档时将ElementTree告诉并将元素附加到列表中,如果元素文本为空则附加" none"作为一个字符串?元素占位符可以这么说。我希望当我显示多个列表的数据时,它将与XML文档中的内容匹配,因为在每个列表的迭代中都考虑了相同数量的元素。

谢谢!

代码示例:

import xml.etree.ElementTree as ET

# file to parse, submit to memory
tree = ET.parse('JuniperXmlConf-Name-NewSSLVPNA.xml')
root = tree.getroot()

#Defining the relevant root by tag.  Children of a Root Tag

user_realms = root[3][0]
user_roles = root[3][1]


#Defining dictionaries Children of Children (subelements)

name = []
idletimeout = []
maxtimeout = []
reminder = []
limit_concurrent_users = []
guaranteed_minimum = []
maximum = []
max_sessions_per_user = []
user_names = []

# Parsing Data into Lists from User_Roles. 
#Notice .text method

for child in user_roles:
    try:
        name.append(child[0].text)
    except IndexError:
        continue
...
...

# Counter displays data as name is argument

i = 0
for value in (name):
    try:
        i += 1
        print("Name: {}, Idletimeout {}, Maxtimeout {}, Reminder {}".format(name[i], 
            idletimeout[i], maxtimeout[i], reminder[i]))
    except IndexError:
        break 

"""
Example of XML:
"""

<users>
        <user-realms>
            <realm>
                <name>Customer Name here</name>
                <authentication-policy>
                    <source-ip>
                        <customized>any-ip</customized>
                        <ips>
                        </ips>
                    </source-ip>
                    <browser>
                        <customized>user-agent here</customized>
                        <user-agent-patterns>
                        </user-agent-patterns>
                    </browser>
    ........
    ........
    <users>
            <user-realms>
                <realm>
                    <name></name>
                    <authentication-policy>
                        <source-ip>
                            <customized>any-ip</customized>
                            <ips>
                            </ips>
                        </source-ip>
                        <browser>
                            <customized>user-agent here</customized>
                            <user-agent-patterns>
                            </user-agent-patterns>
                        </browser>

0 个答案:

没有答案