0
我想對XML中的選定元素進行評論和取消註釋。使用python評論和取消註釋xml元素
xml看起來像這樣。
<ls>
<lo n="x" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="s" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/> <!-- would like to comment this element and uncomment when needed -->
</lo>
<lo n="v" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="h" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/> <!--- would like to comment this element and uncomment when needed-->
</lo>
<Root l="I">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</Root>
</ls>
我從標籤中的最後一個孩子,但我不知道如何在需要的時候發表評論的特定元素並取消。
這是我到目前爲止的代碼:(不預期)
from lxml import etree
tree = etree.parse(r'C:\stop.xml')
for logger in tree.xpath('//logger'):
if logger.get('name') == 'h':
for ref in logger.getchildren():
if ref.get('ref') == 'STDOUT':
ref.append(etree.Comment(' '))
tree.write(r'C:\Log_start.xml', xml_declaration=True, encoding='UTF-8')
輸出
<ls>
<lo n="x" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="s" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"/> <!-- would like to comment this element and uncomment when needed -->
</lo>
<lo n="v" add="b" l="D">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</lo>
<lo n="h" add="b" l="D">
<myconf conf="rf"/>
<myconf conf="st"><!-- --></myconf> <!--- would like to comment this element and uncomment when needed-->
</lo>
<Root l="I">
<myconf conf="rf"/>
<!-- <myconf conf="st"/> -->
</Root>
</ls>
任何幫助將不勝感激!
我有更新的代碼和出來,我越來越。這不是預期! – tgcloud