#dom(文档对象模型) :把解析的xml整个加载到内存,组织成object树。
# dom解析案例:
# from xml.dom.minidom import parse
# domTree=parse("persons.xml")
# print(domTree)
# #得到根节点
# root=domTree.documentElement;
# print(root)
# #得到需要的节点
# person=root.getElementsByTagName("person")
# print(person)
# for p in person: print(p.getElementsByTagName("name")[0].childNodes[0].data)
from xml.dom.minidom import parse
rootTree = parse('7月2号xml.xml')
root = rootTree.documentElement
student = root.getElementsByTagName('student')
list1 = []
for stu in student:
name = stu.getElementsByTagName('stuname')[0].childNodes[0].data
age = stu.getElementsByTagName('stuage')[0].childNodes[0].data
sex = stu.getElementsByTagName('stusex')[0].childNodes[0].data
id = stu.getAttribute('id')
list1.append(id)
list1.append(name)
list1.append(age)
list1.append(sex)
a = list1[0:4]
b = list1[4:8]
def end(x):
dic1 = {}
list2 = ['Id','name', 'age', 'sex']
count = 0
for i in x:
dic1[list2[count]] = i
count += 1
return dic1
# mylist = []
# mylist.append(end(a))
# mylist.append(end(b))
mylist = [end(a),end(b)]
print(mylist)
print('-------------------分割线-------------------')
from xml.dom.minidom import parse
rootTree = parse('7月2号xml.xml')
root = rootTree.documentElement
student = root.getElementsByTagName('student')
list1 = []
for stu in student:
dic1 = {}
name = stu.getElementsByTagName('stuname')[0].childNodes[0].data
age = stu.getElementsByTagName('stuage')[0].childNodes[0].data
sex = stu.getElementsByTagName('stusex')[0].childNodes[0].data
id = stu.getAttribute('id')
dic1['name'] = name
dic1['age'] = age
dic1['sex'] = sex
dic1['id'] = id
list1.append(dic1)
print(list1)
print('-------------------分割线-------------------')
from xml.dom.minidom import parse
class Student:
def __init__(self,id=None,name=None,age=None,sex=None):
self.id = id
self.name = name
self.age = age
self.sex = sex
def __repr__(self):
return self.id+'\t'+self.name+'\t'+'\t'+self.age+'\t'+self.sex
rootTree = parse('7月2号xml.xml')
root = rootTree.documentElement
student = root.getElementsByTagName('student')
list1 = []
for stu in student:
name = stu.getElementsByTagName('stuname')[0].childNodes[0].data
age = stu.getElementsByTagName('stuage')[0].childNodes[0].data
sex = stu.getElementsByTagName('stusex')[0].childNodes[0].data
id = stu.getAttribute('id')
a = Student(id,name,age,sex)
list1.append(a)
for i in list1:
print(i)
# if len(self.name.encode('utf-8'))<=8:
# return self.id+'\t'+self.name+'\t'+'\t'+self.age+'\t'+self.sex
# else:
# self.id + '\t' + self.name + '\t' + self.age + '\t' + self.sex