What is the best way to change text contained in an XML file using Python?

Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:

<?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>

I want to change the text value of 'foo' to 'bar' resulting in the following:

<?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>

Once I am done, I want to save the changes.

What is the easiest and simplest way to accomplish all this?


Asked by: Elian155 | Posted: 05-10-2021






Answer 1

Use Python's minidom

Basically you will take the following steps:

  1. Read XML data into DOM object
  2. Use DOM methods to modify the document
  3. Save new DOM object to new XML document

The python spec should hold your hand rather nicely though this process.

Answered by: Oliver285 | Posted: 06-11-2021



Answer 2

This is what I wrote based on @Ryan's answer:

from xml.dom.minidom import parse
import os

# create a backup of original file
new_file_name = 'MyData.xml'
old_file_name = new_file_name + "~"
os.rename(new_file_name, old_file_name)

# change text value of element
doc = parse(old_file_name)
node = doc.getElementsByTagName('myElement')
node[0].firstChild.nodeValue = 'bar'

# persist changes to new file
xml_file = open(new_file_name, "w")
doc.writexml(xml_file, encoding="utf-8")
xml_file.close()

Not sure if this was the easiest and simplest approach but it does work. (@Javier's answer has less lines of code but requires non-standard library)

Answered by: Miller454 | Posted: 06-11-2021



Answer 3

For quick, non-critical XML manipulations, i really like P4X. It let's you write like this:

import p4x
doc = p4x.P4X (open(file).read)
doc.myElement = 'bar'

Answered by: Adelaide729 | Posted: 06-11-2021



Answer 4

You also might want to check out Uche Ogbuji's excellent XML Data Binding Library, Amara: http://uche.ogbuji.net/tech/4suite/amara

(Documentation here: http://platea.pntic.mec.es/~jmorilla/amara/manual/)

The cool thing about Amara is that it turns an XML document in to a Python object, so you can just do stuff like:

record = doc.xml_create_element(u'Record')

nameElem = doc.xml_create_element(u'Name', content=unicode(name))

record.xml_append(nameElem)

valueElem = doc.xml_create_element(u'Value', content=unicode(value))

record.xml_append(valueElem

(which creates a Record element that contains Name and Value elements (which in turn contain the values of the name and value variables)).

Answered by: Lucas741 | Posted: 06-11-2021



Similar questions

pygame - Running Python code contained in a string

I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events. My plan was to have a text editor in the character builder that let you write code similar to: if key == K_a: ## Move left pass elif key == K_d: ## Move right pass I will retrieve the contents of the text editor...


python - Self contained classes with Qt

I've been trying to make my classes completely self contained, but I'm having some problems, which are probably coming from my missing something that everybody else knew first off... Anyway, take this example: class Main_Window (QtGui.QMainWindow): def __init__ (self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_bookingSystemMain() self.ui.setupUi(self)...


python - Pythonic way to sort list of objects by a dict value (by key) contained within the object

I'm seeking advice on doing the following in a more pythonic way. Consider: class MyObj(object): def __init__(self): self.dict_properties = {} Suppose I've got a list which contains multiple MyObj instances: mylist = [&lt;__main__.MyObj object at 0x1005e3b90, ...] Now i want to sort mylist based on the value of a certain ke...


python - How to check if a list is contained inside another list without a loop?

Is there any builtins to check if a list is contained inside another list without doing any loop? I looked for that in dir(list) but found nothing useful.


python - Escape quotes contained within certain html tags

I've done a mysqldump of a large database, ~300MB. It has made an error though, it has not escaped any quotes contained in any &lt;o:p&gt;...&lt;/o:p&gt; tags. Here's a sample: ...Text here\' escaped correctly, &lt;o:p&gt; But text in here isn't. &lt;/o:p&gt; Out here all\'s well again... Is it possible to write a script (preferably in Python, but I'll take anything!) that wou...


In python, what is contained in the info property of a module object?

I'm looking into creating a Plugin structure for a program and making it so even the core library is treated as plugins. in my research I came across this code that is dynamically importing modules. def __initialize_def(self, module): """Attempt to load the definition""" # Import works the same for py files and package modules so strip! if module.endswith(".py"): name = module [:-3] ...


Python Numpy Matrix - Return the value contained in the matrix?

I have a 1x1 matrix that contains a value. I want just the value. matrix([[-0.16666667+0.66666667j]]) I want the complex number inside that matrix. How do I get it?


Concat all the text files and their content contained in all the .zip files in a text file using Python

I am trying to write a program that would read all files in a folder and output all of their contents into one single file. The files are ziped with the .gz extension. I managed to read one file but not all its contents and not the rest of the files. Here is my code: import glob, gzip, re import pickle filed = open('Logs.txt', 'w') logfilenames = glob.glob('*.gz') logformat = re.compile(r'^\S+ \S+ \...


python - get file list of files contained in a zip file

I have a zip archive: my_zip.zip. Inside it is one txt file, the name of which I do not know. I was taking a look at Python's zipfile module ( http://docs.python.org/library/zipfile.html ), but couldn't make too much sense of what I'm trying to do. How would I do the equivalent of 'double-clicking' the zip file to g...


Bold searched text that is contained in a string with Python

Example If the user searches "car" I would like the output to look like Find your favorite car today, car sale for next 2 days. Notice that car is bolded. Google does it: What's the best way to go about doing this in Python? The bolding is in HTML.






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top