Commenting and uncommenting XML via Python

转载:

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

 from xml.dom import minidom

 xml = """\
<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>
""" def comment_node(node):
comment = node.ownerDocument.createComment(node.toxml())
node.parentNode.replaceChild(comment, node)
return comment def uncomment_node(comment):
node = minidom.parseString(comment.data).firstChild
comment.parentNode.replaceChild(node, comment)
return node doc = minidom.parseString(xml).documentElement comment_node(doc.getElementsByTagName('ant')[-1]) xml = doc.toxml() print 'comment_node():\n'
print xml
print doc = minidom.parseString(xml).documentElement comment = doc.lastChild.previousSibling print 're-parsed comment:\n'
print comment.toxml()
print uncomment_node(comment) print 'uncomment_node():\n'
print doc.toxml()
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>
 
上一篇:vue 实现tab切换动态加载不同的组件


下一篇:Git_学习_11_Git rebase合并提交信息