import sys
from xml.dom.minidom import Document
import xml.dom.minidom
from xml.dom.minidom import Node
def read_xml():
doc = xml.dom.minidom.parse("c:\\myXML.xml")
for node in doc.getElementsByTagName("country"):
print "Country: "+node.getAttribute("name")
for node2 in node.getElementsByTagName("city"):
print "City: "+node2.getAttribute("name")
for node3 in node2.childNodes:
print "City data: "+node3.data
def create_xml():
doc = Document()
main = doc.createElement("main")
doc.appendChild(main)
mglroot = doc.createElement("country")
mglroot.setAttribute("id","1");
mglroot.setAttribute("name","Mongolia");
mglroot.setAttribute("type","country");
main.appendChild(mglroot)
mglcityUb = doc.createElement("city")
mglcityUb.setAttribute("id","1");
mglcityUb.setAttribute("name","Ulaanbaatar");
mglcityUb.setAttribute("type","city");
mglcityUb.appendChild(doc.createTextNode("Ulaanbaatar hot ni anh 1000 ond uusgen bguulagdsan"))
mglroot.appendChild(mglcityUb)
mglcityDark = doc.createElement("city")
mglcityDark.setAttribute("id","2");
mglcityDark.setAttribute("name","Darkhan");
mglcityDark.setAttribute("type","city");
mglcityDark.appendChild(doc.createTextNode("Darkhan hot ni anh 1000 ond uusgen bguulagdsan"))
mglroot.appendChild(mglcityDark)
chnroot = doc.createElement("country")
chnroot.setAttribute("id","2");
chnroot.setAttribute("name","China");
chnroot.setAttribute("type","country");
main.appendChild(chnroot)
chnrootBe = doc.createElement("city")
chnrootBe.setAttribute("id","1");
chnrootBe.setAttribute("name","Beijing");
chnrootBe.setAttribute("type","city");
chnrootBe.appendChild(doc.createTextNode("Beijing hot ni anh 1000 ond uusgen bguulagdsan"))
chnroot.appendChild(chnrootBe)
chnrootSh = doc.createElement("city")
chnrootSh.setAttribute("id","2");
chnrootSh.setAttribute("name","Shanghai");
chnrootSh.setAttribute("type","city");
chnrootSh.appendChild(doc.createTextNode("Shanghai hot ni anh 1000 ond uusgen bguulagdsan"))
chnroot.appendChild(chnrootSh)
print doc.toprettyxml(indent=" ")
f = open("c:\\myXML.xml", "w")
try:
f.write(doc.toprettyxml(indent=" "))
finally:
f.close()
return doc
if __name__ == '__main__':
print "-----------XML CREATE--------";
create_xml()
print "-----------XML READ--------";
read_xml()
Ч. Эрдэнэбат
2011-3-29
No comments:
Post a Comment