delete from pattern to pattern if it contains match

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Apr 25 06:37:39 EDT 2016


harirammanohar at gmail.com writes:

> On Monday, April 25, 2016 at 3:19:15 PM UTC+5:30, hariram... at gmail.com wrote:

[- -]

>> Here is the code:
>> 
>> import xml.etree.ElementTree as ET
>> ET.register_namespace("", "http://xmlns.jcp.org/xml/ns/javaee")
>> tree = ET.parse('sample.xml')
>> root = tree.getroot()
>> 
>> for servlet in root.findall('servlet'):
>>         servletname = servlet.find('servlet-name').text
>>         if servletname == "controller":
>>                 root.remove(servlet)
>> 
>> tree.write('output.xml')

[- -]

> By the way i didnt get any error message and i am using version 3.4.3

Right. The parsing succeeds but no 'servlet' elements are found and the
loop simply has no effect. I may be missing some technical detail, but I
think the 'servlet' elements in the document are in the default
namespace (because one was declared) while your .findall and .find calls
are looking for a 'servlet' element that is in no namespace at all. I
seem to remember that there is such a distinction in XML.



More information about the Python-list mailing list