python中如何解析xml文档

  在实际的应用中,处理xml是很重要也很常用的,相应的处理方法也是多种多样的,本文专注于通用性的xml处理;但为了简单起见,仅包括python中的xml.dom.minidom模块。
  xml.dom.minidom是python中处理xml的一个轻量级接口,但很实用。

1)创建xml对象
  xml应用一般以创建xml对象为起点,使用minidom创建xml对象很简单,可以传入的参数有3类:文件名、文件对象、字符串
  例如:
  1. #-*-encoding:utf-8-*-
  2. from xml.dom.minidom import parse, parseString
  3. fileName = 'example.xml'
  4. dom1 = parse(fileName) # parse an XML file by name
  5. datasource = open(fileName)
  6. dom2 = parse(datasource)   # parse an open file
  7. dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')
  xml文档如下:
  1. <?xml version='1.0' encoding='utf-8'?>
  2. <parent>
  3.     <childs name='childs'>
  4.         <child name='1' />
  5.         <child name='2' />
  6.     </childs>
  7. </parent>
  从上文可以看出,使用字符串构造xml对象时,不需要第一行的xm文档声明;如果使用第一行的话,很不幸的,会抛出一个这样的异常:parser.Parse(string, True) xml.parsers.expat.ExpatError: XML or text declaration not at start of entity

  具体地,其调用方式为:
  1>xml.dom.minidom.parse(filename or file[, parse])
  2>xml.dom.minidom.parseString(string[, parse])
  上述两个函数会返回一个Document对象,上面的parse表示一个SAX2对象,什么意思,大家想想就明白了额。

注意:当xml操作完成之后,切记 删除变量。因为某些版本的Python不支持循环引用变量的垃圾收集,清除dom变量可以使用dom对象的unlink()函数。
例如:
  1. dom1.unlink()
  2. dom2.unlink()
  3. dom3.unlink()
2)xml.dom.minidom与DOM Level1标准
  W3C推荐的DOM标准在Python的实现是由xml.dom.minidom支持的,但二者还是存在一些差别的,具体的
  1>node.unlink()
  2>node.writexml( writer [, indent="" [, addindent="" [, newl="" [, encoding="" ] ] ] ])
  3>node.toxml([encoding])
  4>node.toprettyxml( [ indent="" [, newl="" [, encoding="" ] ] ])

  下面是python文档中给出的例子,简单、典型,发上来大家看看。
  1. import xml.dom.minidom
  2. document = """/
  3. <slideshow>
  4. <title>Demo slideshow</title>
  5. <slide><title>Slide title</title>
  6. <point>This is a demo</point>
  7. <point>Of a program for processing slides</point>
  8. </slide>
  9. <slide><title>Another demo slide</title>
  10. <point>It is important</point>
  11. <point>To have more than</point>
  12. <point>one slide</point>
  13. </slide>
  14. </slideshow>
  15. """
  16. dom = xml.dom.minidom.parseString(document)
  17. def getText(nodelist):
  18.     rc = ""
  19.     for node in nodelist:
  20.         if node.nodeType == node.TEXT_NODE:
  21.             rc = rc + node.data
  22.     return rc
  23. def handleSlideshow(slideshow):
  24.     print("<html>")
  25.     handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
  26.     slides = slideshow.getElementsByTagName("slide")
  27.     handleToc(slides)
  28.     handleSlides(slides)
  29.     print("</html>")
  30. def handleSlides(slides):
  31.     for slide in slides:
  32.         handleSlide(slide)
  33. def handleSlide(slide):
  34.     handleSlideTitle(slide.getElementsByTagName("title")[0])
  35.     handlePoints(slide.getElementsByTagName("point"))
  36. def handleSlideshowTitle(title):
  37.     print("<title>%s</title>" % getText(title.childNodes))
  38. def handleSlideTitle(title):
  39.     print("<h2>%s</h2>" % getText(title.childNodes))
  40. def handlePoints(points):
  41.     print("<ul>")
  42.     for point in points:
  43.         handlePoint(point)
  44.     print("</ul>")
  45. def handlePoint(point):
  46.     print("<li>%s</li>" % getText(point.childNodes))
  47. def handleToc(slides):
  48.     for slide in slides:
  49.         title = slide.getElementsByTagName("title")[0]
  50.         print("<p>%s</p>" % getText(title.childNodes))
  51. handleSlideshow(dom)
  另外,xml.dom.minidom也有一些没有实现的东西,例如:
  • DOMTimeStamp
  • DocumentType
  • DOMImplementation
  • CharacterData
  • CDATASection
  • Notation
  • Entity
  • EntityReference
  • DocumentFragment


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值