3.sax from xml.sax import ContentHandler from xml.sax import parse class book: def __init__(self,bname=None,price=None,author=None): self.bname=bname self.price=price self.author=author def __str__(self): return '名字:%s,价格:%s,作者:%s'%(self.bname,self.price,self.author) bks = [] class handle(ContentHandler): def __init__(self): self.tag = '' def startDocument(self): pass def startElement(self, name, attrs): self.tag = name if self.tag=='book': self.book = book() def characters(self, content): if self.tag=='bname': self.book.bname=content if self.tag=='price': self.book.price=content if self.tag=='author': self.book.author=content def endElement(self, name): if name=='book': bks.append(self.book) self.tag='' def endDocument(self): pass h = handle() parse('book.xml',h) bks = sorted(bks,key=lambda x:x.price,reverse=False) for p in bks: print(p) 2.etree from xml.etree.ElementTree import * class book: def __init__(self,bname=None,price=None,author=None): self.bname=bname self.price=price self.author=author def __str__(self): return '名字:%s,价格:%s,作者:%s'%(self.bname,self.price,self.author) bks = [] root = parse('book.xml') books = root.findall('book') for b in books: bk = book() bk.bname = b.find('bname').text bk.price = b.find('price').text bk.author = b.find('author').text bks.append(bk) for bk in bks: print(bk) 1.dom from xml.dom.minidom import parse tree=parse('book.xml') root=tree.documentElement books=root.getElementsByTagName('book') for b in books: bname = b.getElementsByTagName('bname')[0].childNodes[0].data price = b.getElementsByTagName('price')[0].childNodes[0].data author = b.getElementsByTagName('author')[0].childNodes[0].data print(bname,price,author)
1.15
最新推荐文章于 2024-03-01 14:46:41 发布