Elementtree,检查元素是否具有某个父元素?

时间:2013-07-01 14:52:06

标签: python xml elementtree

我正在解析xml文件:http://pastebin.com/fw151jQN 我希望在复制中阅读它并将其写入一个新文件,其中一些已修改,很多未修改,并且很多都被忽略了。作为初始传递,我想找到某个xml,并将其写入一个未更改的新文件。

以下是最初感兴趣的xml部分:

<COMMAND name="shutdown"
        help="Shutdown the selected interface">
        <CONFIG priority="0x7F01" />
        <ACTION>
        /klas/klish-scripts/interfaces.py conf -i ${iface} --enable 0
        </ACTION>
    </COMMAND>

    <COMMAND name="no shutdown"
        help="Enable the selected interface">
        <CONFIG operation="unset" pattern="shutdown"/>
        <ACTION>
        /klas/klish-scripts/interfaces.py conf -i ${iface} --enable 1
        </ACTION>
    </COMMAND>

我的代码在

下面
#!/usr/bin/python -tt

import xml.etree.ElementTree as ET
tree = ET.parse('interface_range_test.xml')
root = tree.getroot()
namespaces = {'command': 'http://clish.sourceforge.net/XMLSchema}COMMAND','config': 'http://clish.sourceforge.net/XMLSchema}CONFIG'}

all_links = tree.findall('.//')

for i in all_links: 
    if namespaces['command'] in i.tag:
        if i.attrib['name'] == "shutdown":
            print i.attrib       
    if namespaces['config'] in i.tag: 
        print i.attrib

输出:

{'name': 'shutdown', 'help': 'Shutdown the selected interface'}
{'priority': '0x7F01'}
{'pattern': 'shutdown', 'operation': 'unset'}

这会读入文件,我可以找到关机信息,现在我想找到CONFIG信息,然后是action信息及其文本,但是当我搜索时CONFIG 1}} shutdownno shutdown的信息。这种情况会发生在很多xml中,很多都有相同的格式。

关机:     {'priority':'0x7F01'} 没有关机:     {'pattern':'shutdown','operation':'unset'}

如何指定要查看的内容,我可以查看此信息的父级吗?或者我可以检查其上方超级元素的子项(http://clish.sourceforge.net/XMLSchema}COMMAND)吗?

1 个答案:

答案 0 :(得分:2)

您可以搜索所有COMMANDS作为节点(元素),并从那里获取CONFIG信息,例如

import xml.etree.ElementTree as ET
tree = ET.parse('interface_range_test.xml')
root = tree.getroot()

for command in root.iter("{http://clish.sourceforge.net/XMLSchema}COMMAND"):
    subs = list(command.iter('{http://clish.sourceforge.net/XMLSchema}CONFIG'))
    if len(subs) > 0: #we found CONFIG
        print command.tag, command.attrib, subs[0].tag, subs[0].attrib

你会得到:

{http://clish.sourceforge.net/XMLSchema}COMMAND {'name': 'shutdown', 'help': 'Shutdown the selected interface'} {http://clish.sourceforge.net/XMLSchema}CONFIG {'priority': '0x7F01'}
{http://clish.sourceforge.net/XMLSchema}COMMAND {'name': 'no shutdown', 'help': 'Enable the selected interface'} {http://clish.sourceforge.net/XMLSchema}CONFIG {'pattern': 'shutdown', 'operation': 'unset'}
顺便说一句,如果你需要处理大的xml文件,我建议使用lxml,它也有ElementTree compatible interface,但比python的标准xml库快得多。

相关问题