2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > python解析xml文件操作实例

python解析xml文件操作实例

时间:2022-12-01 07:28:55

相关推荐

python解析xml文件操作实例

后端开发|Python教程

python,解析,xml文件

后端开发-Python教程

本文实例讲述了python解析xml文件操作的实现方法。分享给大家供大家参考。具体方法如下:

易语言防误报源码,vscode怎么删除,ubuntu更改目录名字,tomcat存放目录,sqlite fts4,百度贴吧插件中心,前端后台框架怎么搭,Python爬虫酒店数据,php iis 安装,通过网站seo操作,征婚交友类网站源码,网页源代码显示密码,单页商品详情模板源码,win10静态页面模板,cs 管理系统 毕业论文,地方门户程序有哪些lzw

xml文件内容如下:

秒赞源码详细说明,vscode 怎么跑项目,台电安装ubuntu,tomcat记录请求报文,sqlite的数据库删除恢复,golong爬虫,php正则 正整数,潍城seo优化服务,网站登记模板,短信通知集合模板lzw

sample xml thingma xiaoju Springs Widgets, Inc.FirstI think widgets are greate.You should buy lots of them foromSpirngy Widgts, Inc

头像源码打包,Ubuntu默认数字锁定,tomcat端口占用的原因,爬虫难么,php凉了 没工作,seo研究中心超逸seolzw

python代码:

from xml.dom import minidom, Node import re, textwrap class SampleScanner: """""" def __init__(self, doc):"""Constructor"""assert(isinstance(doc, minidom.Document))for child in doc.childNodes: if child.nodeType == Node.ELEMENT_NODE and \ child.tagName == "book": self.handle_book(child) def handle_book(self, node):for child in node.childNodes: if child.nodeType != Node.ELEMENT_NODE: continue if child.tagName == "title": print "Book titile is:", self.gettext(child.childNodes) if child.tagName == "author": self.handle_author(child) if child.tagName == "chapter": self.handle_chapter(child) def handle_chapter(self, node):number = node.getAttribute("number")print "number:", numbertitle_node = node.getElementsByTagName("title")print "title:", self.gettext(title_node)for child in node.childNodes: if child.nodeType != Node.ELEMENT_NODE: continue if child.tagName == "para": self.handle_chapter_para(child) def handle_chapter_para(self, node):company = ""company = self.gettext(node.getElementsByTagName("company"))print "chapter:para:company", company def handle_author(self, node):for child in node.childNodes: if child.nodeType != Node.ELEMENT_NODE: continue if child.tagName == "name": self.handle_author_name(child) if child.tagName == "affiliation": print "affiliation:", self.gettext(child.childNodes) def handle_author_name(self, node):first = ""last = ""for child in node.childNodes: if child.nodeType != Node.ELEMENT_NODE: continue if child.tagName == "first": first = self.gettext(child.childNodes) if child.tagName == last: last = self.gettext(child.childNodes) print "firstname:%s,lastname:%s" % (first, last) def gettext(self, nodelist):retlist = []for node in nodelist: if node.nodeType == Node.TEXT_NODE: retlist.append(node.wholeText) elif node.hasChildNodes: retlist.append(self.gettext(node.childNodes)) return re.sub(\s+, " ", \.join(retlist)) if __name__=="__main__": doc = minidom.parse("simple.xml") sample = SampleScanner(doc)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。