在Python中返回xml文档中给定对象的所有标记和值

时间:2016-02-17 13:05:10

标签: python xml

我有xml看起来像这样......

<CONFIG2>
    <OBJECT id="{2D3474AA-9A0F-4696-979C-1BCE9350F3BD}" type="3" name="Test2" rev="1">
        <RULEITEM>
            <ID>{BF7D00C5-57BC-4187-9B07-064BA5744A12}</ID>
            <PROPERTIES>
                <columnname/>
                <columnvalue/>
                <days>|</days>
                <enabled>1</enabled>
                <eventdate>0001-01-01</eventdate>
                <eventtime>00:00:00</eventtime>
                <function>average</function>
                <parameters/>
                <stattype>standard</stattype>
            </PROPERTIES>
            <ITEM>
                <ID>{61C82F62-8F31-4754-A705-7CCBB34C6FD4}</ID>
                <PROPERTIES>
                    <actionindex>0</actionindex>
                    <actiontype>eventlog</actiontype>
                    <severity>error</severity>
                </PROPERTIES>
            </ITEM>
        </RULEITEM>
        <PROPERTIES>
            <groups>|</groups>
        </PROPERTIES>
    </OBJECT>

我正在尝试返回OBJECT和/ OBJECT中的所有内容。

例如,我想返回OBJECT的所有标签和值,其中type =“3”和name =“test2”。

这是我目前的python脚本......

import xml.etree.ElementTree as ET
tree = ET.parse(r'C:\Users\User\Desktop\xml\config.xml')
root = tree.getroot()

objectType = input("What object type are you looking for?: ")

for item in root.findall('OBJECT'):
    if item.attrib['type'] == objectType:
        print(item.get('name'))

objectName = input("What is the name of the object you are looking for?: ")

for item in root.findall('OBJECT'):
    if item.attrib['type'] == objectType and item.get('name') == objectName:
        print(list(item))

这会返回......

 <Element "RULEITEM' at 0x00064F3C0>, <Element 'PROPERTIES' at 0x0064FB40>

我喜欢它返回整个对象以及所有标签和值。有谁知道我怎么能做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:0)

考虑使用(findall())对所有OBJECT's子孙和孙子孙等进行另一次//*迭代来调整第二个循环。此外,考虑附加到预定义列表而不是list()(这会破坏循环文本项的每个字符)并调整它以删除None值(即空节点)。最后,使用节点的tagtext属性:

... same code as above...

values = []
for item in root.findall('OBJECT'):
    if item.attrib['type'] == objectType and item.get('name') == objectName:
        for data in root.findall("OBJECT//*"):
            if data.text is not None:
                values.append(data.tag + ': ' + data.text)

for v in values:
    print(v)

#What object type are you looking for?: 3
#Test2
#What is the name of the object you are looking for?: Test2
#RULEITEM: 
#            
#ID: {BF7D00C5-57BC-4187-9B07-064BA5744A12}
#PROPERTIES: 
#                
#days: |
#enabled: 1
#eventdate: 0001-01-01
#eventtime: 00:00:00
#function: average
#stattype: standard
#ITEM: 
#                
#ID: {61C82F62-8F31-4754-A705-7CCBB34C6FD4}
#PROPERTIES: 
#                    
#actionindex: 0
#actiontype: eventlog
#severity: error
#PROPERTIES: 
#            
#groups: |