I am new to Python programming . I have a xml file in which one snippet is as below .
<relationship name="a_to_b">
<containment>
<parent>
<hasClass name="a" />
</parent>
<child>
<hasClass name="b" />
</child>
</containment>
</relationship>
Now I have to update this section with the below content .
<relationship name="a_to_b">
<containment>
<parent>
<hasClass name="a">
<mimName>top</mimName>
</hasClass>
</parent>
<child>
<hasClass name="b">
<mimName>top</mimName>
</hasClass>
</child>
</containment>
</relationship>
I am using ElmentTree module . How can I achieve this . Python version 2.6 .
I am using below code .
tree = ET.ElementTree(file=xml) ;
root=tree.getroot() ;
print("Root tag of xml : "+root.tag) ;
#child_of_root=root;
#print("Root tag attribute of xml : "+root.attrib) ;
def fun(root):
#if root.tag is not 'relationship':
for child_of_root in root :
#print("Tag : "+child_of_root.tag) ;
attribut=child_of_root.attrib ;
#print "Value : %s" % attribut.get('name')
if (child_of_root.tag == 'hasClass' and attribut.get('name') == 'MeContext') or (child_of_root.tag == 'hasClass' and attribut.get('name') == 'ManagedElement') :
print(child_of_root.tag,attribut.get('name')) ;
new_data = ET.SubElement(child_of_root, 'mimName');
new_data.text = 'Top'
fun(child_of_root)
fun(root);
Use xml.etree.ElementTree.SubElement
to add tags within another tag. Copying from Python.org ->
>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>
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.