2

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?

3
  • 1
    Can you provide some example input/code and not an image? Commented Nov 1, 2019 at 10:15
  • 1
    You should not post code or sample data as an image because... Commented Nov 1, 2019 at 13:49
  • Thank you for the suggestion @Parfait. I will keep the points in mind Commented Nov 6, 2019 at 9:02

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.