2017-02-16 115 views
0

我花了一些时间研究这个,我就空白了。动态添加/删除Python中的注释ElementTree

我对Python完全陌生,我试图通过我的XML文件,基本上如果某些东西不活跃注释掉一个特定的元素,如果再次活动取消注释。检查激活与否是好的,只是随后的评论进入或退出,我打了墙。我使用python 2.7

我的结构相当简单:

<?xml version="1.0" encoding="utf-8"?> 
<smil xmlns="http://www.w3.org/2001/SMIL20/Language"> 
    <head> 
    <meta name="a" content="some stuff" /> 
    <meta name="b" content="things and stuff" /> 
    <meta name="c" content="rubbish stuff" /> 
    <groupStuff id="foo"> 
     <meta name="thing" content="wibble" /> 
    </groupStuff> 
    <groupStuff id="bar"> 
     <meta name="thing" content="bibble" /> 
    </groupStuff> 
    </head> 
    <body> 
    </body> 
</smil> 

所以,如果不活动注释掉节点,那么如果主动带回。

我认为这将是相当简单的,可能是,但我完全陷入

回答

0

你可以在技术上与它的字符串表示的注释节点替换元素:

#!/usr/bin/env python 
import xml.etree.ElementTree as ET 

root = ET.XML("""<?xml version="1.0" encoding="utf-8"?> 
<smil xmlns="http://www.w3.org/2001/SMIL20/Language"> 
    <head> 
    <meta name="a" content="some stuff" /> 
    <meta name="b" content="things and stuff" /> 
    <meta name="c" content="rubbish stuff" /> 
    <groupStuff id="foo"> 
     <meta name="thing" content="wibble" /> 
    </groupStuff> 
    <groupStuff id="bar"> 
     <meta name="thing" content="bibble" /> 
    </groupStuff> 
    </head> 
    <body> 
    </body> 
</smil>""") 

parent = root.findall(".//*[@name='a']/..")[0] 
child = parent.findall(".//*[@name='a']")[0] 

commented = ET.tostring(child) 

parent.remove(child) 
parent.append(ET.Comment(commented)) 

print ET.tostring(root) 

您可以使用如果订单很重要,则代替insert而不是append

取消注释可能需要使用一些标记来区分禁用的元素和真正的注释。但基本上你会将注释数据解析为自己的元素,并以类似的方式将其替换到树中。