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')]
    
  • 相关阅读:
    ERP需求调研之仓库物料管理十问十答
    Oracle ERP系统月结与年结流程探讨
    利用fnd_flex_keyval包轻松获取关键性弹性域组合描述字段
    AR/AP 借项通知单和贷项通知单的区别
    EBS Profile的定义与使用
    EBS System Profile 常用清单
    月结经验摘抄1
    Oracle 总帐模块会计业务周期
    MFC自动注册ODBC数据源
    RichEditView自写WriteColorMessage
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3131144.html
Copyright © 2011-2022 走看看