使用 Python/ElementTree 为 XML 中的元素插入节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4788633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert a node for an element in XML with Python/ElementTree
提问by prosseek
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
当值小于5时,我需要遍历XML树添加子元素。 比如这个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>
this XML.
这个 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>
How can I do that with Python's ElementTree?
我怎样才能用 Python 的 ElementTree 做到这一点?
采纳答案by scoffey
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:
您可能打错了,因为在示例中,错误元素被附加为值为 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
Given this input:
鉴于此输入:
<?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>
This is is the output:
这是输出:
<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>
回答by Mark Tolonen
ElementTree's iter(or getiteratorfor Python <2.7) willl recursively return all the nodes in a tree, then just test for your condition and create the SubElement:
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'))

