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')]
    
  • 相关阅读:
    关于位运算(转)
    计蒜客第三场
    数组与指针
    计蒜客第二场
    指针概念
    爬楼梯(动态规划)
    线性表基本操作的实现(合并)
    4123=喵帕斯之天才少女
    3889=神奇的函数
    1586=计算组合数
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3131144.html
Copyright © 2011-2022 走看看