[Tutor] Generating/Parsing XML

tee chwee liong tcl76 at hotmail.com
Tue Apr 12 08:28:53 CEST 2011


hi, 
 
i'm a bit stuck here. i have a code dict1.py that writes to an xml and another script parsedict1.py to parse the content of the xml. 
when i write it to the xml i wrote it as dictionary but since it can't accept dict format i convert it to string. 
below is output  of the parsedict1.py when i print it out. 
 
>>>(None, '{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}')
>>>(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
 
Questions:

Why it shows as None and not LINK or Lanestat?
How can i modify the code to show LINK or Lanestat? 
How can i extract the key in the dictionary since there are 2 elements only. for eg: if i print a[1], it will show {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}. 
    i want to be able to extract info like this: Link [1] = 1, just like how it is done in dictionary. 
 
pls help to advise.
 
thanks
tcl
p/s: attached code for dict1.py, parsedict1.py, dict1.xml
 
dict1.py code:
import elementtree.ElementTree as ET
def port_status():    
    a=1
    b=2
    c=3
    d=4
    e=5
    f=6
    return (a,b,c,d,e,f)
call_port=port_status()
link_status={1:call_port[0], 2:call_port[1], 3:call_port[2], 4:call_port[3], 5:call_port[4], 6:call_port[5]}
lane_status={1:call_port[0]+1, 2:call_port[1]+2, 3:call_port[2]+3, 4:call_port[3]+4, 5:call_port[4]+5, 6:call_port[5]+6}
print link_status
print lane_status
###write to xml
root = ET.Element("Test")
head1 = ET.SubElement(root, "Default_Config")
title = ET.SubElement(head1, "LINK")
title.text = str(link_status)
title = ET.SubElement(head1, "Lanestat")
title.text = str(lane_status)
tree = ET.ElementTree(root)
tree.write("C:\\Python25\\myscript\\cmm\\dict1.xml")
 
parsedict1.py code:
import elementtree.ElementTree as ET
tree = ET.parse("dict1.xml")
doc = tree.getroot()

for elem in doc.findall('Default_Config/LINK'):
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a
for elem in doc.findall('Default_Config/Lanestat'):
    
    #print elem.get('LINK'), elem.text
    a=elem.get('LINK'), elem.text
    print a 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110412/cee2e90e/attachment.html>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: dict1.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20110412/cee2e90e/attachment.ksh>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: dict1.xml
Type: text/xml
Size: 154 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110412/cee2e90e/attachment.xml>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: parsedict1.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20110412/cee2e90e/attachment-0001.ksh>


More information about the Tutor mailing list