使用Python / ElementTree在XML中插入元素的节点 [英] Insert a node for an element in XML with Python/ElementTree

查看:691
本文介绍了使用Python / ElementTree在XML中插入元素的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当值小于5时,我需要遍历XML树以添加子元素。
例如,可以将该XML修改为

I need to traverse the XML tree to add sub element when the value is less than 5. For example, this XML can be modified into

<?xml version="1.0" encoding="UTF-8"?>
<A value="45">
    <B value="30">
        <C value="10"/>
        <C value ="20"/>
    </B>
    <B value="15">
        <C value = "5" />
        <C value = "10" />
    </B>
</A>

此XML。

<?xml version="1.0" encoding="UTF-8"?>
<A value="45">
    <B value="30">
        <C value="10"/>               
        <C value ="20"/>
    </B>
    <B value="15">
        <C value = "5"><D name="error"/></C>
        <C value = "10" />
    </B>
</A>

如何使用Python的ElementTree做到这一点?

How can I do that with Python's ElementTree?

推荐答案

您可能输入了错字,因为在示例中,错误元素被附加为元素值为10(不小于5)的子元素。但是,我认为是这样的想法:

You probably made a typo because in the example, an error element is appended as the child of an element whose value is 10, which is not less than 5. But I think this is the idea:

#!/usr/bin/env python

from xml.etree.ElementTree import fromstring, ElementTree, Element

def validate_node(elem):
    for child in elem.getchildren():
        validate_node(child)
        value = child.attrib.get('value', '')
        if not value.isdigit() or int(value) < 5:
            child.append(Element('D', {'name': 'error'}))

if __name__ == '__main__':
    import sys
    xml = sys.stdin.read() # read XML from standard input
    root = fromstring(xml) # parse into XML element tree
    validate_node(root)
    ElementTree(root).write(sys.stdout, encoding='utf-8')
            # write resulting XML to standard output

给出以下输入:

<?xml version="1.0" encoding="UTF-8"?>
<A value="45">
    <B value="30">
        <C value="1"/>
        <C value="20"/>
    </B>
    <B value="15">
        <C value="5" />
        <C value="10" />
        <C value="foo" />
    </B>
</A>

这是输出:

<A value="45">
    <B value="30">
        <C value="1"><D name="error" /></C>
        <C value="20" />
    </B>
    <B value="15">
        <C value="5" />
        <C value="10" />
        <C value="foo"><D name="error" /></C>
    </B>
</A>

这篇关于使用Python / ElementTree在XML中插入元素的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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