remove child in DOM??

Fredrik Lundh fredrik at pythonware.com
Sun Dec 12 04:10:31 EST 2004


Juliano Freitas wrote:

> how can i remove a child in DOM ?

node.removeChild(child)

where both node and child are DOM nodes.

> for example, i have thi xml below:
> <root>
>  <user>
>     <name> juliano </name>
>  </user>
> <root>
>
> and i want to remove the <name> element:
> <root>
>  <user>
>  </user>
> <root>
>
> how can  i do this??

here's a brute force solution:

from xml.dom.minidom import Node, parseString

dom = parseString(xml)

node = dom.getElementsByTagName("user")[0] # get first user
for subnode in node.childNodes:
    if subnode.nodeType == Node.ELEMENT_NODE and subnode.tagName == "name":
        node.removeChild(subnode)
        break # must break if modifying the list we're iterating over

(I'm sure some DOM expert can come up with a better solution)

notes:

1) the [0] will raise an exception if there are no "user" elements in the tree;
for production code, you can either handle the exception, check the length
of the element list before indexing, or use a "one-shot" for-loop:

for node in dom.getElementsByTagName("user"):
    ...
    break # only process the first element

2) the removeChild() method modifies the childNodes list, so you must leave
the loop after the first remove.  to remove multiple children, you have to use a
separate loop counter (and increment it only if you're not removing anything),
or scan the list backwards.

3) the above example leaves surrounding whitespace in the tree.  in other words,
you'll get

    <root>
      <user>

      </user>
    </root>

instead of

<root>
  <user></user>
</root>

to get rid of the whitespace, you need to add an extra pass that looks for unnecessary
text nodes for which len(data.strip()) is zero.

4) obligatory elementtree example:

    user = dom.find("root/user")
    user.remove(user.find("name"))

</F> 






More information about the Python-list mailing list