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():\n'
28 print xml
29 print
30 
31 doc = minidom.parseString(xml).documentElement
32 
33 comment = doc.lastChild.previousSibling
34 
35 print 're-parsed comment:\n'
36 print comment.toxml()
37 print
38 
39 uncomment_node(comment)
40 
41 print 'uncomment_node():\n'
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>
 

 

posted on 2013-12-05 18:13  lpthread  阅读(386)  评论(0编辑  收藏  举报