python - 使用 ElementTree 的递归 XML 解析 python

标签 python xml recursion elementtree

我正在尝试使用 Python ElementTree 解析以下 XML 以生成如下输出。我正在尝试为顶级元素编写模块来打印它们。然而,这有点棘手,因为类别元素可能有也可能没有属性,并且类别元素内部可能有类别元素。

我在本主题中提到了上一个问题,但它们不包含具有相同名称的嵌套元素

我的代码: http://pastebin.com/Fsv2Xzqf

work.xml:
<suite id="1" name="MainApplication">
<displayNameKey>my Application</displayNameKey>
<displayName>my Application</displayName>
<application id="2" name="Sub Application1">
<displayNameKey>sub Application1</displayNameKey>
<displayName>sub Application1</displayName>
<category id="2423" name="about">
<displayNameKey>subApp.about</displayNameKey>
<displayName>subApp.about</displayName>
<category id="2423" name="comms">
<displayNameKey>subApp.comms</displayNameKey>
<displayName>subApp.comms</displayName>
<property id="5909" name="copyright" type="string_property" width="40">
<value>2014</value>
</property>
<property id="5910" name="os" type="string_property" width="40">
<value>Linux 2.6.32-431.29.2.el6.x86_64</value>
</property>
</category>
<property id="5908" name="releaseNumber" type="string_property" width="40">
<value>9.1.0.3.0.54</value>
</property>
</category>
</application>
</suite>

输出应该如下:

Suite: MainApplication
    Application: Sub Application1
        Category: about
            property: releaseNumber | 9.1.0.3.0.54
            category: comms
                property: copyright | 2014
                property: os | Linux 2.6.32-431.29.2.el6.x86_64

任何指向正确方向的指示都会有所帮助。

最佳答案

import xml.etree.ElementTree as ET
tree = ET.ElementTree(file='work.xml')

indent = 0
ignoreElems = ['displayNameKey', 'displayName']

def printRecur(root):
    """Recursively prints the tree."""
    if root.tag in ignoreElems:
        return
    print ' '*indent + '%s: %s' % (root.tag.title(), root.attrib.get('name', root.text))
    global indent
    indent += 4
    for elem in root.getchildren():
        printRecur(elem)
    indent -= 4

root = tree.getroot()
printRecur(root)

输出:

Suite: MainApplication
    Application: Sub Application1
        Category: about
            Category: comms
                Property: copyright
                    Value: 2014
                Property: os
                    Value: Linux 2.6.32-431.29.2.el6.x86_64
            Property: releaseNumber
                Value: 9.1.0.3.0.54

这是我能在 5 分钟内到达的最接近的位置。您应该递归地调用处理器函数,这会很小心。您可以从这一点改进 :)


您还可以为每个标签定义处理函数,并将它们全部放入字典中以便于查找。然后你可以检查你是否有一个适合该标签的处理函数,然后调用它,否则继续盲目打印。例如:

HANDLERS = {
    'property': 'handle_property',
    <tag_name>: <handler_function>
}

def handle_property(root):
    """Takes property root element and prints the values."""
    data = ' '*indent + '%s: %s ' % (root.tag.title(), root.attrib['name'])
    values = []
    for elem in root.getchildren():
        if elem.tag == 'value':
            values.append(elem.text)
    print data + '| %s' % (', '.join(values))

# printRecur would get modified accordingly.
def printRecur(root):
    """Recursively prints the tree."""
    if root.tag in ignoreElems:
        return

    global indent
    indent += 4

    if root.tag in HANDLERS:
        handler = globals()[HANDLERS[root.tag]]
        handler(root)
    else:
        print ' '*indent + '%s: %s' % (root.tag.title(), root.attrib.get('name', root.text))
        for elem in root.getchildren():
            printRecur(elem)

    indent -= 4

上面的输出:

Suite: MainApplication
    Application: Sub Application1
        Category: about
            Category: comms
                Property: copyright | 2014
                Property: os | Linux 2.6.32-431.29.2.el6.x86_64
            Property: releaseNumber | 9.1.0.3.0.54

我发现这比在代码中放置大量 if/else 更有用。

关于python - 使用 ElementTree 的递归 XML 解析 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28194703/

相关文章:

Python3如何按一定精度向上(向下)舍入

Javascript,一个简单的递归函数

java - 二项式系数。递归树。如何避免多次计算相同的值

Python输出numpy数组作为base64编码的字符串而不是jpg

python - 使方法在包中的更高级别可用

xml - 检查祖先属性值是否是某个值

xml - Maven 构建失败,Liquibase : cvc-elt. 1 找不到元素声明

python - .after() 方法递归

python - 使用 python ruamel-yaml 保持 YAML 文件的偏移缩进

java - 当我单击按钮更改 Activity 时应用程序崩溃