zoukankan      html  css  js  c++  java
  • lxml.etree 教程3:Elements carry attributes as a dict

    XML元素支持属性,你可以在Element工厂里面直接创建它们。

    >>> root = etree.Element("root", interesting="totally")
    >>> etree.tostring(root)
    b'<root interesting="totally"/>'
    

     属性不过是没有顺序的名称-值对,所以一个方便的处理它们的方式是通过类字典的元素接口。

    >>> print(root.get("interesting"))
    totally
    
    >>> print(root.get("hello"))
    None
    >>> root.set("hello", "Huhu")
    >>> print(root.get("hello"))
    Huhu
    
    >>> etree.tostring(root)
    b'<root interesting="totally" hello="Huhu"/>'
    
    >>> sorted(root.keys())
    ['hello', 'interesting']
    
    >>> for name, value in sorted(root.items()):
    ...     print('%s = %r' % (name, value))
    hello = 'Huhu'
    interesting = 'totally'
    

     对于其它案例,比如你想做元素查找或者访问一个真实的类字典的对象。你可以使用attrib属性

    >>> attributes = root.attrib
    
    >>> print(attributes["interesting"])
    totally
    >>> print(attributes.get("no-such-attribute"))
    None
    
    >>> attributes["hello"] = "Guten Tag"
    >>> print(attributes["hello"])
    Guten Tag
    >>> print(root.get("hello"))
    Guten Tag
    

     注意attrib是一个Element自己支持的类字典对象。这意味着任何对Elements的改变将反应到attrib,反之亦然。这也意味着XML树一直存在内存里面只要其中一个Elements的attrib在使用。为了得到一个独立影像的属性,而不依赖于XML树,把它拷贝到字典

    >>> d = dict(root.attrib)
    >>> sorted(d.items())
    [('hello', 'Guten Tag'), ('interesting', 'totally')]
    
  • 相关阅读:
    SQL SERVER代码生成器必备
    jquery实现ajax提交表单信息
    linux下的守护进程
    异步在单进程系统中的重要性
    php常用函数(持续更新)
    根据html容器大小和显示文字多少调节字体大小
    弹出框插件
    本地连接虚拟机上面的redis
    Flume学习——BasicTransactionSemantics
    Flume学习——BasicChannelSemantics
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3131144.html
Copyright © 2011-2022 走看看