zoukankan      html  css  js  c++  java
  • Commenting and uncommenting XML via Python

    转载:

    http://stackoverflow.com/questions/8764017/commenting-and-uncommenting-xml-via-python

     1 from xml.dom import minidom
     2 
     3 xml = """
     4 <target depends="create-build-dir" name="build-Folio">
     5    <property name="project.name" value="Folio"/>
     6    <ant antfile="build.xml" dir="Folio/FolioUI" inheritall="false" target="package"/>
     7    <ant antfile="build.xml" dir="Folio/Folio" inheritall="false" target="package"/>
     8 </target>
     9 """
    10 
    11 def comment_node(node):
    12     comment = node.ownerDocument.createComment(node.toxml())
    13     node.parentNode.replaceChild(comment, node)
    14     return comment
    15 
    16 def uncomment_node(comment):
    17     node = minidom.parseString(comment.data).firstChild
    18     comment.parentNode.replaceChild(node, comment)
    19     return node
    20 
    21 doc = minidom.parseString(xml).documentElement
    22 
    23 comment_node(doc.getElementsByTagName('ant')[-1])
    24 
    25 xml = doc.toxml()
    26 
    27 print 'comment_node():
    '
    28 print xml
    29 print
    30 
    31 doc = minidom.parseString(xml).documentElement
    32 
    33 comment = doc.lastChild.previousSibling
    34 
    35 print 're-parsed comment:
    '
    36 print comment.toxml()
    37 print
    38 
    39 uncomment_node(comment)
    40 
    41 print 'uncomment_node():
    '
    42 print doc.toxml()
    43 print


    Output:

    
    
    comment_node():<target depends="create-build-dir" name="build-Folio"><property name="project.name" value="Folio"/><ant antfile="build.xml" dir="Folio/FolioUI" inheritall="false" target="package"/><!--<ant antfile="build.xml" dir="Folio/Folio" inheritall="false" target="package"/>--></target>
    
    re-parsed comment:<!--<ant antfile="build.xml" dir="Folio/Folio" inheritall="false" target="package"/>-->
    
    uncomment_node():<target depends="create-build-dir" name="build-Folio"><property name="project.name" value="Folio"/><ant antfile="build.xml" dir="Folio/FolioUI" inheritall="false" target="package"/><ant antfile="build.xml" dir="Folio/Folio" inheritall="false" target="package"/></target>
     
  • 相关阅读:
    if控制器+循环控制器+计数器,控制接口分支
    前置处理器
    逻辑控制器
    配置元件
    基础元件
    docker etcdctl报错:etcdctl No help topic for 'put'
    celery定时执行ansible api返回为空的问题
    Ansible+Jenkins+Gitlab搭建及配置
    进击的Python【第十六章】:Web前端基础之jQuery
    进击的Python【第十五章】:Web前端基础之DOM
  • 原文地址:https://www.cnblogs.com/lpthread/p/3460136.html
Copyright © 2011-2022 走看看