【发布时间】:2017-08-29 07:52:43
【问题描述】:
我想对 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>
任何帮助将不胜感激。!
【问题讨论】:
-
我已经更新了代码和我得到的输出。!这是意料之外的!
标签: xml python-2.7 lxml xml-comments