confused with xml and minidom

Andrew Clover and-google at doxdesk.com
Thu Mar 25 07:59:54 EST 2004


Guy Robinson <guy at NOSPAM.r-e-d.co.nz> wrote:

> table.childnode('tbody').getElementsByTagname('tr') doesn't work.

There is no such method as 'childnode'. childNodes is a list of all
children of tbody, including tr elements and text nodes representing the
whitespace in the document. You can search through it manually:

  def getChildElementsByTagName(parentNode, tagnem):
    els= []
    for child in parentNode.childNodes:
      if child.nodeType==child.ELEMENT_NODE and child.tagname==tagname:
        els.append(child)
    return els

  tbody= table.getChildElementsByTagName('tbody')[0]
  trs= tbody.getChildElementsByTagName('tr')

or just use getElementsByTagName:

  tr= table.getElementsByTagName('tr')[0]

Note that getElementsByTagName works recursively, so for example in the
case of nested tables you'll get more items returned than just the direct
children.

Also in the standard DOM the NodeList objects returned by
getElementsByTagName are supposed to be 'live' and will change as the
document is updated. This isn't supported in minidom, but might be in
other implementations, so it's a good idea to use list() to convert the
NodeList to a static non-updating Python list before using it if you're
going to be changing the document at the same time.

> Delete this row and insert the new rows?

document.createDocumentFragment() a new fragment and appendChild the new
row elements to it, then tbody.replaceChild(fragment, tr).

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/



More information about the Python-list mailing list