zoukankan      html  css  js  c++  java
  • Python全栈开发:XML与parse对比

    #!/usr/bin/env python
    # -*- coding;utf-8 -*-
    """
        ET.XML和ET.parse的对比
            1、返回对象差异:
                ET.XML:Returns an Element instance,xml.etree.ElementTree.Element对象不具有写的功能
                ET.parse:返回ElementTree对象,xml.etree.ElementTree.ElementTree对象才具有写的功能
            2、传入参数差异:
                XML(text, parser=None):*text* is a string containing XML data
                parse(source, parser=None):*source* is a filename or file object containing XML data
    """
    from xml.etree import ElementTree as ET
    
    # 方式一
    # 打开文件,读取XML内容
    str_xml = open("first.xml").read()
    
    # 将字符串解析成xml特殊对象,放入内存,root1代表xml的根节点,它是Element的对象,没有可写功能,不能写入文件
    root1 = ET.XML(str_xml)  # 只能解析字符串,不能解析文件,Returns an Element instance
    print(root1, type(root1))
    # 错误:root1.write("file3.xml") 原因:xml.etree.ElementTree.Element' object has no attribute 'write'
    # root1为xml的根节点,代表xml字符串
    # 要保存的话要使用根节点(Element的对象)创建ElementTree对象
    tree1 = ET.ElementTree(root1)  # 返回ElementTree对象
    print(tree1, type(tree1))
    tree1.write("tree1.xml")
    
    # 方式二
    # 直接解析xml文件,tree具有可读功能,可以使用write方法写入文件
    tree2 = ET.parse("first.xml")  # 解析文件,不能解析字符串,返回ElementTree对象
    
    # 获取xml文件的根节点,Return root element of this tree
    root2 = tree2.getroot()
    # 错误:root2.write("file4.xml") 原因:xml.etree.ElementTree.Element' object has no attribute 'write'
    print(root2, type(root2))
    tree2.write("tree2.xml")
    

      

  • 相关阅读:
    Spring入门之一-------实现一个简单的IoC
    SpringBoot+SpringSecurity之多模块用户认证授权同步
    SpringBoot+SpringSecurity之如何forword到登录页面
    SpringBoot实现OAuth2认证服务器
    SpringBoot安全认证Security
    SpringBoot的ApplicationRunner和CommandLineRunner
    SpringBoot通过ApplicationArguments获取args
    安利demo
    多路canvas的mapbox gl
    复合canvas叠加显示
  • 原文地址:https://www.cnblogs.com/nixingguo/p/6496525.html
Copyright © 2011-2022 走看看