tags:

views:

72

answers:

1

I want to find all nodes in a xml file that have a certain tag-name, lets say "foo". If those foo-tags have them thelves child nodes with node-name "bar", then I want to remove those nodes. The result should be written to a file.

<myDoc>
  <foo>
    <bar/> // remove this one
  </foo>
  <foo>
    <anyThing>
      <bar/> // don't remove this one
    </anyThing>
  </foo>
</myDoc> 

Thanx for any hints. As the tag indicates, I would like to do this with python.

A: 

You can use ElementTree:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse('in.xml')

foos = tree.findall('foo')
for foo in foos:
  bars = foo.findall('bar')
  for bar in bars:
    foo.remove(bar)

tree.write('out.xml')
miles82
this works grate but only when bar has no content. If if have <bar>false</bar>this does not work. How can I solve that?
nebenmir
Are you sure? I've tried with "<bar>false</bar>" and it works.
miles82
true. my bad, was a typo. sorry for that. So now it works perfectly, thank you very much.
nebenmir