使用Python/ElementTree在XML中为元素插入节点

9

我需要遍历XML树,在值小于5时添加子元素。 例如,可以将此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" />
        <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实现这个功能?

相关链接:http://stackoverflow.com/questions/4788958/set-the-value-of-xml-file-recursively-with-python-elementtree - jfs
是否可以有多个<D>子元素?您是否考虑过在出现问题的元素上添加“error”属性的选项? - John Machin
2个回答

13

你可能打错了字,因为在这个例子中,错误元素被追加到一个值为10且不小于5的元素的子级中。但我认为这是这个例子的意思:

#!/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>

我关心的是,一个全深度的循环是否会迭代新添加的子元素?例如,如果for循环使用for node in list(tree.getroot())完成,并且在迭代时某个节点被添加到某个位置。 - n611x007
这个程序的运行方式是 cat file.xml | python script.py 吗?我试过了,可以运行,但我想知道是否还有其他方法。 - fedorqui

2
"ElementTree"的"iter"(或对于Python版本小于2.7的使用"getiterator")将递归返回树中的所有节点,然后只需测试您的条件并创建"SubElement"即可。"
from xml.etree import ElementTree as ET
tree = ET.parse(input)
for e in tree.getiterator():
    if int(e.get('value')) < 5:
        ET.SubElement(e,'D',dict(name='error'))

2
新增的元素是否会被迭代器返回?如果是,我该如何区分新元素和已存在的元素? - n611x007

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接