首页 / XML / 通过Python评论和取消注释XML
通过Python评论和取消注释XML
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了通过Python评论和取消注释XML,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2473字,纯文字阅读大概需要4分钟。
内容图文
![通过Python评论和取消注释XML](/upload/InfoBanner/zyjiaocheng/720/451c1692ae534d3da1bc5e8169f3ab1c.jpg)
我想知道一种使用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
输出:
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>
内容总结
以上是互联网集市为您收集整理的通过Python评论和取消注释XML全部内容,希望文章能够帮你解决通过Python评论和取消注释XML所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。