zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    win11 千呼万唤 原生安卓体验及安装方法
    (转)pytorch和torch框架对比(区别 联系)
    AI深度学习部分框架了解
    有趣的USB接口和颜色分类
    后疫情时代读《浪潮之巅》第四版 读书笔记
    关于win11 VBS(基于虚拟化的安全性) 相关研究中
    Windows IPsec IP安全策略
    Element ui复杂表格(多级表头、尾行求合、单元格合并)前端导出excel
    es的常用字段类型和查询
    oom常见的解决方式
  • 原文地址:https://www.cnblogs.com/stellar/p/5980590.html
Copyright © 2011-2022 走看看