简体   繁体   中英

python ElementTree remove issue

I have xml file as following:

<plugin-config>
   <properties>
      <property name="AZSRVC_CONNECTION" value="diamond_plugins@AZSRVC" />
      <property name="DIAMOND_HOST" value="10.0.230.1" />
      <property name="DIAMOND_PORT" value="3333" />
   </properties>
   <pack-list>
      <vsme-pack id="monthly_50MB">
         <campaign-list>
            <campaign id="2759" type="SOB" />
            <campaign id="2723" type="SUBSCRIBE" />
         </campaign-list>
      </vsme-pack>
      <vsme-pack id="monthly_500MB">
         <campaign-list>
            <campaign id="3879" type="SOB" />
            <campaign id="3885" type="SOB" />
            <campaign id="2724" type="SUBSCRIBE" />
         <campaign id="1111" type="COB" /></campaign-list>
      </vsme-pack>
   </pack-list>
</plugin-config>

And trying to run this Python script to remove 'campaign' with specific id.

import xml.etree.ElementTree as ET

tree = ET.parse('pack-assign-config.xml')
root = tree.getroot()
pack_list = root.find('pack-list')

camp_list = pack_list.find(".//vsme-pack[@id='{pack_id}']".format(pack_id=pack_id)).find('campaign-list').findall('campaign')

for camp in camp_list:
    if camp.get('id') == '2759':
        camp_list.remove(camp)

tree.write('out.xml')

I run script but out is the same as input file, so does not remove element.

Issue :

this is wrong way to find the desired node . you are searching for vsme-pack and the trying to find campaign-list and campaign ? which incorrect format.

 camp_list = pack_list.find(".//vsme-pack[@id='{pack_id}']".format(pack_id=pack_id)).find('campaign-list').findall('campaign') 

Fixed Code Example

here is the working code which removes the node from xml

 import xml.etree.ElementTree as ET root = ET.parse('pack-assign-config.xml') # Alternatively, parse the XML that lives in 'filename_path' # tree = ElementTree.parse(filename_path) # root = tree.getroot() # Find the parent element of each "weight" element, using XPATH for parent in root.findall('.//pack-list/'): # Find each weight element for element in parent.findall('campaign-list'): for camp_list in element.findall('campaign'): if camp_list.get('id') == '2759' or camp_list.get('id') == '3879' : element.remove(camp_list) root.write("out.xml") 

hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM