RSS
热门关键字:
当前位置 : 主页>编程开发>Python>列表

可爱的 Python:DOM 的动态性

来源:我要研发网 作者:BusinessWeekly.Asia 时间:2008-05-18 点击:




     return
     py_obj
    # Main test
dom_obj = FileReader(
    "quotes.xml").document
py_obj = pyobj_from_dom(dom_obj)
     if
     __name__ ==
    "__main__":
     
     print
     pyobj_printer(py_obj) 字串9

  这里的关注焦点应该是函数 pyobj_from_dom() ,特别是起实际作用的 xml.dom 方法 .get_childNodes() 。在 pyobj_from_dom() 中,我们直接抽取标记之间的所有文本,将它放到保留属性 .PCDATA 中。对于任何遇到的嵌套标记,我们创建一个新属性,其名称与标记匹配,并将一个列表分配给该属性,这样就可以潜在地包含在在父代块中多次出现的标记。当然,使用列表要维护在 XML 文档中遇到的标记的顺序。

字串4

  除了使用旧的 pyobj_printer() 类属函数(或者,更复杂和健壮的函数)之外,我们可以使用正常的属性记号来访问 py_obj 的元素。

字串5

  Python 交互式会话

字串8

>>>
     from
     try_dom3
     import
     *
>>> py_obj.quotations[0].quotation[3].source[0].PCDATA
    'Guido van Rossum, '
字串3

  重新安排 DOM 树

字串7

  DOM 的一大优点是它可以让程序员以非线性方式对 XML 文档进行操作。由相匹配的开/关标记括起的每一块都只是 DOM 树中的一个“节点”。当以类似于列表的方式维护节点以保留顺序信息时,则顺序并没有什么特殊之处,也并非不可改变。我们可以轻易地剪下某个节点,嫁接到 DOM 树的另一个位置(如果 DTD 允许,甚至嫁接到另一层上)。或者添加新的节点、删除现有节点,等等。

字串4

  try_dom4.py    """Manipulate the arrangement of nodes in a DOM object
"""
    
     from
     try_dom3
     import
     *
    #-- Var 'doc' will hold the single "trunk"
doc = dom_obj.get_childNodes()[0]
    #-- Pull off all the nodes into a Python list
# (each node is a block, or a whitespace text node)
nodes = []
     while
     1:
     
     try
    : node = doc.removeChild(doc.get_childNodes()[0])
     
     except
    :
     break
  nodes.append(node)
    #-- Reverse the order of the quotations using a list method
# (we could also perform more complicated operations on the list:
# delete elements, add new ones, sort on complex criteria, etc.)
nodes.reverse()
    #-- Fill 'doc' back up with our rearranged nodes
    
     for
     node

字串4

     in
     nodes:
    # if second arg is None, insert is to end of list
  doc.insertBefore(node, None)
    #-- Output the manipulated DOM
    
     print
     dom_obj.toxml()
字串3

字串5

  如果我们将 XML 文档只看作一个文本文件,或者使用一个面向序列的模块(如 xmllib 或 xml.sax),那么在以上几行中执行对 quotation 节点的重新安排操作将引出一个值得考虑的问题。然而如果使用 DOM,则问题就如同对 Python 列表执行的任何其它操作一样简单。 字串7

字串3

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册
相关文章