'''
Created on 2012-5-25
@author: salomon
'''
import xml.dom.minidom as minidom
dom = minidom.parse("E:\\test.xml")
root = dom.getElementsByTagName("Schools") #The function getElementsByTagName returns NodeList.
print(root.length)
for node in root:
print("Root element is %s。" %node.tagName)# 格式化输出,与C系列语言有很大区别。
schools = node.getElementsByTagName("School")
for school in schools:
print(school.nodeName)
print(school.tagName)
print(school.getAttribute("Name"))
print(school.attributes["Name"].value)
classes = school.getElementsByTagName("Class")
print("There are %d classes in school %s" %(classes.length, school.getAttribute("Name")))
for mclass in classes:
print(mclass.getAttribute("Id"))
for student in mclass.getElementsByTagName("Student"):
print(student.attributes["Name"].value)
print(student.getElementsByTagName("English")[0].nodeValue) #这个为什么啊?
print(student.getElementsByTagName("English")[0].childNodes[0].nodeValue)
student.getElementsByTagName("English")[0].childNodes[0].nodeValue = 75
f = open('new.xml', 'w', encoding = 'utf-8')
dom.writexml(f,encoding = 'utf-8')
f.close()
ElementTree
目前搜到的ElementTree的信息较少,目前不知道其工作机制。有资料显示ElementTree近乎一种轻量级的DOM,但是ElementTree 所有的 Element 节点的工作方式是一致的。它很类似于C#中的XpathNavigator。
'''
Created on 2012-5-25
@author: salomon
'''
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("E:\\test.xml")
root = tree.getroot()
print(root.tag)
print(root[0].tag)
print(root[0].attrib)
schools = root.getchildren()
for school in schools:
print(school.get("Name"))
classes = school.findall("Class")
for mclass in classes:
print(mclass.items())
print(mclass.keys())
print(mclass.attrib["Id"])
math = mclass.find("Student").find("Scores").find("Math")
print(math.text)
math.set("teacher", "bada")
tree.write("new.xml")