简体   繁体   中英

How to add a subchild on a xml file using xml.etree.ElementTree

I'm following following the official documentation about how could i modify an existing xml file in order to add a subchild value inside the record child.

Original xml file:

<Values version="2.0">
  <value name="system_type">osx</value>
  <record name="service">
    <value name="threads">1</value>
  </record>
</Values>

Current code:

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')

Current output:

<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>

desired xml file:

<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>

I want to start with one remark: the input XML seems wrong (semantically), because you have a root node Values , which has children value and record (which doesn't seem to belong here).

But, considering that the XML is correct, then you don't want to add the newly created node directly under Values node, but under record (which is a child of Values ). To find out that node, [Python 3]: findall ( match, namespaces=None ) is used.

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)

After running the code,

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM