Changing the value of an element in an existing XML file using the DOM

I am trying to find examples of how to modify the existing value of an xml XML element.

Using the following xml example:

<book>
  <title>My Book</title>
  <author>John Smith</author>
</book>

If I wanted to replace the value of the author element "John Smith" with "Jim Johnson" in a Python script using the DOM, how would I do it? I tried to find examples on this, but could not do it. Any help would be greatly appreciated.

Regards, Rylic

+3
source share
1 answer

suggesting

s = '''
<book>
  <title>My Book</title>
  <author>John Smith</author>
</book>'''

The DOM will look like this:

from xml.dom import minidom

dom = minidom.parseString(s) # or parse(filename_or_file)
for author in dom.getElementsByTagName('author'):
    author.childNodes = [dom.createTextNode("Jane Smith")]

But I would advise you to look into ElementTree, this will simplify the work with XML:

from xml.etree import ElementTree

et = ElementTree.fromstring(s) # or parse(filename_or_file)
for author in et.findall('author'):
    author.text = "Jane Smith"
+5
source

Source: https://habr.com/ru/post/1737570/


All Articles