Reputation: 102
I have the following xmls (simplified):
Base:
<root>
<child1></child1>
<child2></child2>
</root>
ChildInfo:
<ChildInfo>
<Name>Something</Name>
<School>ElementarySchool</School>
<Age>7</Age>
</ChildInfo>
ExpectedOutput:
<root>
<child1></child1>
<child2>
<ChildInfo>
<Name>Something</Name>
<School>ElementarySchool</School>
<Age>7</Age>
</ChildInfo>
</child2>
</root>
This case is simplified just to provide the functionality I need. The XMls in the real case scenario are really big so creating a subelement line by line is not an option, so parsing a xml file is the only way I can do it.
I have the following until now
pythonfile.py:
import xml.etree.ElementTree as ET
finalScript=ET.parse(r"resources/JmeterBase.xml")
samplerChild=ET.parse(r"resources/JmeterSampler.xml")
root=finalScript.getroot()
samplerChildRoot=ET.Element(samplerChild.getroot())
root.append(samplerChildRoot)
But this is not giving the desired option and in all xml guides the samples are really simple and dont deal with this cases.
Is there a way to load a complete xml file and sabe it as an element that can be added as a whole? or should I just change libraries?
Upvotes: 0
Views: 29
Reputation: 18106
You can load JmeterSampler.xml
directly as Element when using ET.fromstring(...)
, then you just need to append the Element to the place you want:
import xml.etree.ElementTree as ET
finalScript = ET.parse(r"resources/JmeterBase.xml")
samplerChild = ET.fromstring(open(r"resources/JmeterSampler.xml").read())
root = finalScript.getroot()
child2 = root.find('child2')
child2.append(samplerChild)
print (ET.tostring(root, 'utf-8'))
Prints:
<root>
<child1 />
<child2><ChildInfo>
<Name>Something</Name>
<School>ElementarySchool</School>
<Age>7</Age>
</ChildInfo>
</child2>
</root>
Upvotes: 1