使用Python注释掉XML

2024-06-02 09:48:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图(但失败了)从jboss6.2中删除HornetQ配置域.xml文件,而不是在要删除的节周围插入注释,而是设法删除文件中剩余的所有内容。在

到目前为止我掌握的代码是

from xml.dom import minidom
import os, time, shutil

domConf=('/home/test/JBoss/jboss-eap-6.2/domain/configuration/domain.xml')
commentSub=('urn:jboss:domain:messaging:1.4')


now=str(int(time.time())) 
bkup=(domConf+now)
shutil.copy2(domConf, bkup)

xmldoc = minidom.parse(domConf)
itemlist = xmldoc.getElementsByTagName('subsystem')
for s in itemlist:
        if commentSub in s.attributes['xmlns'].value:
            s.parentNode.insertBefore(xmldoc.createComment(s.toxml()), s)
file = open(domConf, "wb")
xmldoc.writexml(file)
file.write('\n')
file.close()

我想说的是-

^{pr2}$

谢谢!在


Tags: 文件importtimedomainxmlnowjbossfile
1条回答
网友
1楼 · 发布于 2024-06-02 09:48:19

您遇到的问题是,您试图注释掉的部分已经包含XML注释。XML中不允许嵌套注释。(有关详细信息,请参见Nested comments in XML?。)

我想你需要做的是:

from xml.dom import minidom
import os, time, shutil

domConf=('/home/test/JBoss/jboss-eap-6.2/domain/configuration/domain.xml')
resultFile='result.xml'
commentSub=('urn:jboss:domain:messaging:1.4')

now=str(int(time.time()))
bkup=(domConf+now)
shutil.copy2(domConf, bkup)

xmldoc = minidom.parse(domConf)
itemlist = xmldoc.getElementsByTagName('subsystem')
for s in itemlist:
        if commentSub in s.attributes['xmlns'].value:
            commentText = s.toxml()
            commentText = commentText.replace(' ', '- -')
            s.parentNode.insertBefore(xmldoc.createComment(commentText), s)
            s.parentNode.removeChild(s)
file = open("result.xml", "wb")
xmldoc.writexml(file)
file.write('\n')
file.close()

shutil.copy2(resultFile, domConf)

这会像您一样查找注释,但在插入之前,会通过将“”替换为“-”来更改任何嵌套的XML注释,使它们不再是注释。(注意,如果取消注释该部分,这可能会破坏XML文件结构。如果你想让它再次解析的话,你必须反转这个过程。)插入之后,脚本删除原始节点。然后它将所有内容写入临时文件,并使用shutil将其复制回原始文件。在

我在我的系统上测试了这一点,使用的是你在下面评论中发布到pastebin的文件,它起作用了。在

请注意,这是一种快速而肮脏的黑客攻击,因为脚本还会在该节中的任何地方用“-”替换“”,如果XML节点中有其他文本,并且其中包含“”,则它也将被替换。。。在

正确的方法可能是使用lxmlelementtree实现,使用lxml's XSL到{a5},然后适当地删除或转换它们,这样就不会弄乱未注释的文本。但这可能超出了你的要求。(Python的内置elementtree没有完整的XSL实现,可能无法用于选择注释。)

相关问题 更多 >