python 处理xml中的注释_通过Python评论和取消注释XML

我想知道一种使用Python在XML中注释和取消注释元素的方法.

我怎么能让它看起来像这样:

然后根据需要再次删除评论…

要么

我正在使用xml.dom中的minidom.我是否需要使用其他XML解析器?宁愿避免使用正则表达式……这将是一场噩梦.

解决方法:

下面的脚本使用xml.dom.minidom并包含注释和取消注释节点的函数:

from xml.dom import minidom

xml = """\

"""

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():

re-parsed comment:

uncomment_node():

标签:minidom,python,xml,xml-parsing,ant

来源: https://codeday.me/bug/20190902/1792076.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值