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

Let's say I have an existing trivial XML file called "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", as a result we get the following:

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

As soon as I finish, I want to save the changes.

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

+4
source share
4 answers

Use Python minidom

Basically you follow these steps:

  • Reading XML data into a DOM object
  • Use the DOM methods to modify the document.
  • Save new DOM object in new XML document

The python spec should hold your hand pretty well, although this process.

+4
source

For quick, non-critical XML manipulations, I really like P4X . This allows you to write like this:

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

Here 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 easiest approach, but it really works. ( @Javier answer has fewer lines of code, but requires a custom library)

+3
source

You might also want to check out Uche Ogbuji, Amara's excellent XML data binding library: 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 into a Python object, so you can just do things 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 containing Name and Value elements (which, in turn, contain name values ​​and variable values)).

+1
source

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


All Articles