Sourav
Sourav

Reputation: 3392

How to add nested child nodes to a parent node in xml documents using python?

I have two xml files snapshot.

Input xml:

input_xml

Desired Output XML:

output_xml

I need to add few child nodes to the parent node with tag <triggers\> using python script.

The example of child nodes to add is highlighted in grey in output.xml snapshot.

Complete tag to replace triggers node.

  <triggers>
    <hudson.triggers.TimerTrigger>
      <spec>1 1 1 1 1</spec>
    </hudson.triggers.TimerTrigger>
  </triggers>

Can anyone help me with the python script for replacing the non-empty tag whenever encountered with above tag using python script?

Upvotes: 2

Views: 3020

Answers (2)

Rithin Chalumuri
Rithin Chalumuri

Reputation: 1839

You can use ET.SubElement to create subelements to a given node. More info here.

Then you can set .text to be the value of that node.

For example, consider the following input xml document:

<root>
  <triggers/>
  <triggers/>
</root>

Try this:

import xml.etree.ElementTree as ET

tree = ET.parse('input.xml')
root = tree.getroot()

#Get all triggers elements
trigger_elements = root.findall('./triggers')

#For each trigger element in your xml document
for trigger in trigger_elements:

    #Make subelement to the initial trigger element
    time_trigger_element = ET.SubElement(trigger, 'hudson.triggers.TimerTrigger')

    #Make subelement to the time trigger elemenent with name 'spec'
    spec_element = ET.SubElement(time_trigger_element, 'spec')

    #Set the text of spec element to 1 1 1 1 1
    spec_element.text = ' '.join(['1']*5)


#Save the xml tree to a file
tree.write("output.xml")

Outputs:

<root>
  <triggers><hudson.triggers.TimerTrigger><spec>1 1 1 1 1</spec></hudson.triggers.TimerTrigger></triggers>
  <triggers><hudson.triggers.TimerTrigger><spec>1 1 1 1 1</spec></hudson.triggers.TimerTrigger></triggers>
</root>

Upvotes: 2

Jack Fleeting
Jack Fleeting

Reputation: 24930

If you want to do it with BeautifulSoup, you can try something like this:

code1 = """   
<triggers/>
"""
code2 = """    
<triggers>
    <hudson.triggers.TimerTrigger>
      <spec>1 1 1 1 1</spec>
    </hudson.triggers.TimerTrigger>
  </triggers>

"""
from bs4 import BeautifulSoup as bs

soup1 = bs(code1)
soup2 = bs(code2)

old = soup1.find('triggers')
new = soup2.find('triggers')
old.replaceWith(new)
print(soup1)

Upvotes: 0

Related Questions