我想知道一种使用 Python 注释和取消注释 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>
我怎样才能让它看起来像这样:
<target depends="create-build-dir" name="build-Folio">
<property name="project.name" value="Folio"/>
<ant antfile="build.xml" dir="Folio/FolioUI" inheritall="false" target="deploy"/>
<!-- <ant antfile="build.xml" dir="Folio/Folio" inheritall="false" target="deploy"/> -->
</target>
然后根据需要再次删除注释...
或者
我正在使用 xml.dom 中的 minidom。我需要使用不同的 XML 解析器吗?宁愿避免使用正则表达式......那将是一场噩梦。
下面的脚本使用xml.dom.minidom
并包括注释和取消注释节点的功能:
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)