• 使用DOM解析xml(python3.4)


    一、DOM(Document Object Model)

    将XML数据在内存中解析成一个树,通过对树的操作来操作XML。

    二、

    XML实例文件movies.xml:

    <collection shelf="New Arrivals">
    <movie title="Enemy Behind">    <!-- 属性(attribute) -->
       <type>War, Thriller</type>    <!-- 元素(element) --> 
       <format>DVD</format>
       <year>2003</year>
       <rating>PG</rating>
       <stars>10</stars>
       <description>Talk about a US-Japan war</description>
    </movie>
    <movie title="Transformers">
       <type>Anime, Science Fiction</type>
       <format>DVD</format>
       <year>1989</year>
       <rating>R</rating>
       <stars>8</stars>
       <description>A schientific fiction</description>
    </movie>
    </collection>

    解析代码:

    from xml.dom.minidom import parse
    import xml.dom.minidom
    
    # 使用minidom解析器打开 XML 文档
    DOMTree = xml.dom.minidom.parse("e:/movies.xml")
    collection = DOMTree.documentElement
    if collection.hasAttribute("shelf"):
       print ("Root element : %s" % collection.getAttribute("shelf"))
    
    # 在集合中获取所有电影
    movies = collection.getElementsByTagName("movie")
    
    # 打印每部电影的详细信息
    for movie in movies:
       print ("*****Movie*****")
       if movie.hasAttribute("title"):
          print ("Title: %s" % movie.getAttribute("title"))
    
       type = movie.getElementsByTagName('type')[0]  # [0]:若存在同名的,用以区分
       print ("Type: %s" % type.childNodes[0].data)  # type.childNodes[0]表示type标签下的第一个内容或者子标签
       format = movie.getElementsByTagName('format')[0]
       print ("Format: %s" % format.childNodes[0].data)
       rating = movie.getElementsByTagName('rating')[0]
       print ("Rating: %s" % rating.childNodes[0].data)
       description = movie.getElementsByTagName('description')[0]
       print ("Description: %s" % description.childNodes[0].data)

    childNodes -----> 嵌套列表???

    三、常用方法:

    minidom.parse(filename)    #加载读取XML文件
     
    doc.documentElement        #获取XML文档对象
     
    node.getAttribute(AttributeName)    #获取XML节点属性值
     
    node.getElementsByTagName(TagName)    #获取XML节点对象集合
     
    node.childNodes    #返回子节点列表。
     
    node.childNodes[index].nodeValue    #获取XML节点值
     
    node.firstChild    #访问第一个节点。等价于pagexml.childNodes[0]
     
    doc = minidom.parse(filename)
    doc.toxml('UTF-8')    #返回Node节点的xml表示的文本
     
    Node.attributes["id"]    #访问元素属性
    a.name    #就是上面的 "id"
    a.value    #属性的值

    http://www.cnblogs.com/kaituorensheng/p/4493306.html

  • 相关阅读:
    Swift入门篇-Hello World
    Swift入门篇-swift简介
    Minecraft 插件 world edit 的cs 命令
    搭建本地MAVEN NEXUS 服务
    MC java 远程调试 plugin 开发
    企业内部从零开始安装docker hadoop 提纲
    javascript 命令方式 测试例子
    ca des key crt scr
    JSF 抽象和实现例子 (函数和属性)
    form 上传 html 代码
  • 原文地址:https://www.cnblogs.com/stellar/p/5980590.html
Copyright © 2020-2023  润新知