xml 解析

xml文件

#------------------------------------------------------------------------------------------------------------------

# test.xml

<?xml version="1.0" encoding="utf-8"?>
<Schools>
    <School Name="XiDian">
        <Class Id="030612">
            <Student Name="salomon">
                <English Teacher="xiashuangxi">"He is graduate from xiangnan."</English>
                <Scores>
                    <Math>98</Math>
                    <English>
                        <English>85</English>
                    </English>
                    <physics>89</physics>
                </Scores>
            </Student>
            <Student Name="Jupiter">
                <Scores>
                    <Math>74</Math>
                    <English>83</English>
                    <physics>69</physics>
                </Scores>
            </Student>
        </Class>
        <Class Id="030611">
            <Student Name="Venus">
                <Scores>
                    <Math>98</Math>
                    <English>85</English>
                    <physics>89</physics>
                </Scores>
            </Student>
            <Student Name="Mars">
                <Scores>
                    <Math>74</Math>
                    <English>83</English>
                    <physics>69</physics>
                </Scores>
            </Student>
        </Class>
    </School>
</Schools>

#----------------------------------------------------------

代碼:

'''

Created on 2012-5-25

@author: salomon
'''

import xml.dom.minidom as minidom


dom = minidom.parse(r"D:\StudyProject\XML\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')
dom.writexml(f,encoding = 'utf-8')
f.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章