我跟随official documentation关注如何修改现有的xml文件,以便在记录子项中添加子项值。
原始xml文件:
<Values version="2.0">
<value name="system_type">osx</value>
<record name="service">
<value name="threads">1</value>
</record>
</Values>
当前代码:
from xml.etree import ElementTree as ET
tree = ET.parse('data.xml')
values = tree.getroot()
list_languages = values.getchildren()
processing = ET.Element('value')
processing.attrib['name'] = 'cpu_use_limit'
processing.text = '20'
values.append(processing)
tree.write('output.xml')
当前输出:
<Values version="2.0">
<value name="system_type">osx</value>
<record name="service">
<value name="threads">1</value>
</record>
<value name="cpu_use_limit">20</value>
</Values>
所需的xml文件:
<Values version="2.0">
<value name="system_type">osx</value>
<record name="service">
<value name="threads">1</value>
<value name="cpu_use_limit">20</value>
</record>
</Values>
答案 0 :(得分:0)
我想从一句话开始:输入 XML 似乎是错误的(语义上),因为你有一个根节点值,它有子节点 value < / em> 和 记录(这似乎不属于此处)。
但是,考虑到 XML 是正确的,那么您不希望直接在 Values 节点下添加新创建的节点,但在 record <下/ em>(这是 Values 的孩子)。要找出该节点,请使用[Python 3]: findall(match, namespaces=None)。
code.py :
from xml.etree import ElementTree as ET
if __name__ == "__main__":
tree = ET.parse("data.xml")
values = tree.getroot()
list_languages = values.getchildren()
processing = ET.Element("value")
processing.attrib["name"] = "cpu_use_limit"
processing.text = "20"
relevant_nodes = values.findall("record")
for relevant_node in relevant_nodes:
relevant_node.append(processing)
tree.write("output.xml", encoding="utf-8", xml_declaration=True)
运行代码后,
的Output.xml :
<?xml version='1.0' encoding='utf-8'?>
<Values version="2.0">
<value name="system_type">osx</value>
<record name="service">
<value name="threads">1</value>
<value name="cpu_use_limit">20</value></record>
</Values>