Python xml文件解析

来源:互联网 发布:医疗网络咨询 编辑:程序博客网 时间:2024/05/23 19:38

(1)xml文件

<?xml version="1.0" encoding="utf-8"?>
<Schools>
    <School Name="XiDian">
        <Class Id="030612">
            <Student Name="salomon">
                <Scores>
                    <Math>98</Math>
                    <English>85</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>

(2)xml文件解析

方法一:

import xml.dom.minidom as minidom

dom = minidom.parse("C:\\Users\\lenovo\\Desktop\\aaa\\my1.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


方法二:

from xml.etree.ElementTree import ElementTree


tree = ElementTree()
tree.parse("C:\\Users\\lenovo\\Desktop\\aaa\\my1.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")

0 0
原创粉丝点击