Skip to content Skip to sidebar Skip to footer

Change Xml Using Python

I have xml file like this: test I need to open it and change test in qweqwe to anoth

Solution 1:

I recommend using lmxl - a simple example is:

from lxml import etree as et

>>> xml="""<lala>
  <blabla>
    <qweqwe>test</qweqwe>
  </blabla>
</lala>
"""
>>> test = et.fromstring(xml)
>>> for i in test.xpath('//qweqwe'):
    i.text = 'adsfadfasdfasdfasdf' # put logic here


>>> print et.tostring(test) # write this to file instead
<lala>
  <blabla>
    <qweqwe>adsfadfasdfasdfasdf</qweqwe>
  </blabla>
</lala>

Solution 2:

As with all the other XML questions on here for python look at lxml

Link: http://lxml.de/


Solution 3:

For tasks like these, I find the minidom built in library to be quick and easy. However, I can't say that I've done extensive comparions of it to various other libraries in terms of speed and memory usage.

I like it cause its light weight, quick to develop with and present since Python 2.0


Solution 4:

Here is a question about modifying the value of an xml element but it shouldn't be too much of a stretch to use the suggested answer to modify the text of an xml element instead.


Solution 5:

If you are trying to change ALL instances of test you can just open the file and look for a string match

so

result = []
f = open("xml file")

 for i in f:
  if i == "<qweqwe>test</qweqwe>":
   i = "<qweqwe>My change</qweqwe>"
  result.append(i)

 f.close()

 f = open("new xml file")
 for x in result:
  f.writeline(x)

Post a Comment for "Change Xml Using Python"