delete from pattern to pattern if it contains match

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Apr 25 08:00:09 EDT 2016


harirammanohar at gmail.com writes:

> On Monday, April 25, 2016 at 4:58:15 PM UTC+5:30, Jussi Piitulainen wrote:
>> harirammanohar at gmail.com writes:
>> 
>> > On Monday, April 25, 2016 at 4:09:26 PM UTC+5:30, Jussi Piitulainen wrote:
>> >> Peter Otten writes:
>> >> 
>> >> > harirammanohar at gmail.com wrote:
>> >> >
>> >> >> Here is the code:
>> >> >
>> >> > Finally ;)
>> >> 
>> >> :)
>> >
>> > name space issue can be resolved registering name space i have no
>> > issue with that, only concern is xml parser has no effect when http
>> > things are added...
>> 
>> No, the parser works fine. Your attempt to register a default namespace
>> didn't work. Those "http things" *are* the namespace issue!
>> 
>> The following version of your code works. *Try it.* It finds the servlet
>> element in the document object, removes it, and writes out XML text
>> without the servlet element. (It seems to invent another namespace
>> prefix. That doesn't change the meaning of the document.)
>> 
>> import xml.etree.ElementTree as ET
>> 
>> ns = { 'x' : "http://xmlns.jcp.org/xml/ns/javaee" }
>> 
>> tree = ET.parse('sample.xml')
>> root = tree.getroot()
>> 
>> for servlet in root.findall('x:servlet', ns):
>>     servletname = servlet.find('x:servlet-name', ns).text
>>     if servletname == "controller":
>>         root.remove(servlet)
>> 
>> tree.write('output.xml')
>
> yup its working well if i include register namespace, else i am
> getting ns:0 in every line of output.xml.

That's a namespace prefix for each element name that is in the default
namespace. If the ET.register_namespace has the effect of making that
the default namespace in the output, fine, you can use it.

The important thing is that you can read your output.xml back in, using
the XML parser, and it has the intended meaning.

> But its removing top line
> <?xml version="1.0" encoding="ISO-8859-1"?>

Not a problem. You can still read your output.xml back in, using the XML
parser, and it will have the same meaning as it would have had with this
declaration.



More information about the Python-list mailing list