用Python注释/取消注释XML子元素

时间:2019-05-14 17:47:02

标签: python xml comments

我正在尝试以编程方式注释/取消注释来自python的XML(子)元素。例如,我要注释掉主机为“ 111.111.111.222”的元素。

 import os
 import xml.etree.ElementTree as ET
 from xml.etree.ElementTree import Comment, tostring  

 xml='''
    <config>
       <ui>...</ui>
       <distributed overwrite-children="true">
           <daemon host="111.111.111.111" port="8888">
                 <service-group name="standalone" />
           </daemon>
           <daemon host="111.111.111.222" port="8888">
                 <service-group name="standalone" />
           </daemon>
           <daemon host="111.111.111.333" port="8888">
                 <service-group name="standalone" />
           </daemon>
        </distributed>
    </config>'''


  try:
        tree = ET.fromstring (xml)
        root = tree.getroot()
  except Exception as ex:
        exit(ex)

  element = root.find(".//distributed/daemon[@host='111.111.111.222']")
  print (element)

  comment_element = Comment(tostring(element))

  root.insert(???, comment_element)  # how to get element index to insert the commented node here?
  root.remove(element)  //throws error as element is not direct child of root?
  print tostring(root)

最终的XML应该看起来像这样(或类似):

<config>
       <ui>...</ui>
       <distributed overwrite-children="true">
           <daemon host="111.111.111.111" port="8888">
                 <service-group name="standalone" />
           </daemon>
           <!--
           <daemon host="111.111.111.222" port="8888">
                 <service-group name="standalone" />
           </daemon>
           -->
           <daemon host="111.111.111.333" port="8888">
                 <service-group name="standalone" />
           </daemon>
        </distributed>
</config>

此外,如果已经注释过某个特定元素,我就需要取消注释。 我正在尝试使用XML库,但任何其他示例都可以使用(例如BeautifulSoup)。

0 个答案:

没有答案