Update element values using xml.dom.minidom

Posted by amnesia-55 on Stack Overflow See other posts from Stack Overflow or by amnesia-55
Published on 2010-03-23T18:55:00Z Indexed on 2010/03/24 2:03 UTC
Read the original article Hit count: 464

Filed under:
|
|

Hello,

I have an XML structure which looks similar to:

<Store>
   <foo>
      <book>
        <isbn>123456</isbn>
      </book>
      <title>XYZ</title>
      <checkout>no</checkout>
   </foo>

   <bar>
      <book>
        <isbn>7890</isbn>
      </book>
      <title>XYZ2</title>
      <checkout>yes</checkout>
   </bar>
</Store>

Using xml.dom.minidom only (restrictions) i would like to

1)traverse through the XML file

2)Search/Get for particular element, depending on its parent

Example: checkout element for author1, isbn for author2

3)Change/Set that element's value

4)Write the new XML structure to a file

Can anyone help here?

Thank you!

UPDATE:

This is what i have done till now

import xml.dom.minidom
checkout = "yes"

def getLoneChild(node, tagname):

  assert ((node is not None) and (tagname is not None))
  elem = node.getElementsByTagName(tagname)
  if ((elem is None) or (len(elem) != 1)):
    return None
  return elem

def getLoneLeaf(node, tagname):

  assert ((node is not None) and (tagname is not None))
  elem = node.getElementsByTagName(tagname)
  if ((elem is None) or (len(elem) != 1)):
    return None
  leaf = elem[0].firstChild
  if (leaf is None):
    return None
  return leaf.data


def setcheckout(node, tagname):

  assert ((node is not None) and (tagname is not None))
  child = getLoneChild(node, 'foo')
  Check = getLoneLeaf(child[0],'checkout')
  Check = tagname
  return Check

doc = xml.dom.minidom.parse('test.xml') 
root = doc.getElementsByTagName('Store')[0]
output = setcheckout(root, checkout)

tmp_config = '/tmp/tmp_config.xml' 
fw = open(tmp_config, 'w')
fw.write(doc.toxml())
fw.close()

© Stack Overflow or respective owner

Related posts about python

Related posts about Xml