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')]
    
  • 相关阅读:
    Parameter Binding in ASP.NET Web API
    Which HTTP methods match up to which CRUD methods?
    ErrorHandling in asp.net web api
    HttpStatusCode
    Autofac Getting Started(默认的构造函数注入)
    Autofac Controlling Scope and Lifetime
    luvit 被忽视的lua 高性能框架(仿nodejs)
    undefined与null的区别
    VsCode中使用Emmet神器快速编写HTML代码
    字符串匹配---KMP算法
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3131144.html
Copyright © 2011-2022 走看看