2017-02-16 116 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

取消註釋可能需要使用一些標記來區分禁用的元素和真正的註釋。但基本上你會將註釋數據解析爲自己的元素,並以類似的方式將其替換到樹中。