Wednesday, January 24, 2018

Python : Copy entire node along with subnodes in XML

Python : Copy entire node along with sub nodes in XML



from xml.etree import ElementTree 
from xml.etree.ElementTree import Element, SubElement, Comment, tostring 
import copy

xml = """<a>
           <b>
            <c>
                <d>India</d>
            </c>
             <c>
                <d>USA</d>
            </c>
              <c>
                <d>China</d>
            </c>
   </b>
 </a>"""

#---------------------
def xml_node_grabber(xml , node_name):
    result=[]
    xml_tree = ElementTree.fromstring(xml)

    for i in xml_tree.findall(".//"+node_name):
        dupe = copy.deepcopy(i) #copy <c> node
        result.append(dupe) #insert the new node
    
    iterator_res=iter(result)
    return (iterator_res)
#------------------------

res=xml_node_grabber(xml, "c")
for i in res:
    print(ElementTree.tostring(i))



Result:

b'<c>\n                <d>India</d>\n            </c>\n             '
b'<c>\n                <d>USA</d>\n            </c>\n              '
b'<c>\n                <d>China</d>\n            </c>\n  

Tuesday, January 16, 2018

Python : Call function using string (similar to Java Reflection API )

Python : Call function using string (similar to Java Reflection API )


# Calling
class animals:
    def dog(self):
        print("bark")
       
    def lion(self):
        print("roar")


obj=getattr(animals(),'dog')
obj()

result :
bark