Sunday 27 October 2013

How to Read and write xml file in python



We can easily Read and write xml in file using python. In python one library is present name xml, in this library some module is there name as etree, dom, sax, parsers. By the help of these modules you can read and write xml in file easily.


We can read and write xml by xml tree or dom

Write xml data in file

import xml
xml_file = open("customer_data.xml", "wb")
xml_file.write('

    
        1
        2008
        141100
        
        
    
    
        4
        2011
        59900
        
    
    
        68
        2011
        13600
')
xml_file.close()

Xml parsing or read xml from file

Example: 1
File customer_data.xml

<Settings>

<ComputerNameIPs value="" name=”” />

<ComputerConfig value="" />

<ComputerTarget value="" />

<ComputerLoginCredentials value="" >
</Settings>
Python code
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

for rank in root.iter(“ComputerNameIPs”):
    rank.attrib["value"]=’Ashish’     #this is for writing
    rank.attrib["name"]=’computer’     
    tree.write('country_data.xml')

for rank in root.iter(“ComputerNameIPs”):
    data=rank.attrib["value"]        #this is for reading
    print data

for roots in root:
    print root.tag	             #it will show all tag which is inside 
    print root.attrib[‘value’]       #it will show any attribute in tag
 
 
Example-2
File customer_data.xml
    
        1
        2008
        141100
        
        
    
    
        4
        2011
        59900
        
    
    
        68
        2011
        13600
        
Python code
 
for child in root:
     print(child.tag, child.attrib)
 
output... 
country {'name': 'Liechtenstein'} 
country {'name': 'Singapore'} 
country {'name': 'Panama'}

print root[0][1].text
 
or 

for country in root.findall('country'):
   if .find('year').text==’2008’:
       rank = country.find('year').text
       print rank
 
output…
  '2008' 

Remove  and appending xml data  

Python code

for roots in root:
	for roo in roots:
  		if roo.tag =='year':
     		   roots.remove(roo)             #this is for removing xml data
     		   tree.write('country_data.xml')

	    newNode1 = ET.Element('rating')
            roots.append(newNode1)               #this is for adding data
            tree.write('country_data.xml')
 


Output...


    
        1
        </ rating >
        141100
        
        
    
    
        4
        59900
        
	</ rating >
    
    
        68
        13600
        
        
	</ rating >
    


Modifying xml data


for rank in root.iter('rank'):
   new_rank = int(rank.text) + 1
   rank.text = str(new_rank)
   rank.set('updated', 'yes')
   tree.write('output.xml')
 
Output...

    
        2
        2008
        141100
        
        
    
    
        5
        2011
        59900
        
    
    
        69
        2011
        13600
        
        
    


How to use web-services in pygtk for desktop application



Suds is a one Lightweight SOAP client module which is used for web services.  We send web request to server by the help of suds, this request will go to server and server will return response in format.


From my perspective I have used suds for desktop application login.  I am using 1 desktop application and I want to login in it with server. Then by suds module it will send login request to server with username password and server will return response-“this username and password are correct or wrong”.


So we can say that with the help of suds module, we can send request to server and get response for any task. It is nothing but web services.

How to use suds


First download suds Lightweight SOAP client module from here--DOWNLOAD  and if you want to read more about suds then go through URL


import suds.metrics as metrics
from suds import WebFault
from suds.client import Client


uid = username
pwd = password
url = 'http://www.thomas-bayer.com/axis2/services/BLZService?wsdl'

client = Client(url) 
print client
data = client.service.Dologin(uid,pwd)
print 'token="%s"' % data



data  will print server response.
If u print client then it will show below result

Suds - version: 0.3.3 build: (beta) R397-20081121

Service (WebServiceTestBeanService) 
tns="http://www.thomas-bayer.com/axis2/services/BLZService?wsdl'
   Prefixes (1):
     ns0 = "http://www.thomas-bayer.com/axis2/services/BLZService?wsdl'   Ports (1):
     (Soap)
       Methods:
         addPerson(Person person, )
         echo(xs:string arg0, )
         getList(xs:string str, xs:int length, )
         getPercentBodyFat(xs:string name, xs:int height, xs:int weight)
         getPersonByName(Name name, )
         hello()
         testExceptions()
         testListArg(xs:string[] list, )
         testVoid()
         updatePerson(AnotherPerson person, name name, )
   Types (23):
     Person
     Name
     Phone
     AnotherPerson

Or second method
 
import urllib2
baseurl = 'http://localhost:7080/'
username = 'myuser'
password = 'mypassword'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, baseurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)

Or 

import urllib
import urllib2

url = 'http://example.com/...'
values = { 'productslug': 'bar','qty': 'bar' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
print result
 
If you guys need any help, then comment below. I will support you.
Thanks