1

I have xml file like this:

<lala>
  <blabla>
    <qweqwe>test</qweqwe>
  </blabla>
</lala>

I need to open it and change test in qweqwe to another value, for example newtest. After it I need to save it like a new xml file. Please help me how to do it in the best way using python?

Andrej
  • 77
  • 1
  • 6
  • 1
    You can use `ElementTree`. There are many examples in the standard documentation. http://docs.python.org/library/xml.etree.elementtree.html – Maksim Skurydzin Oct 04 '12 at 13:50

6 Answers6

2

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>
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

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

Link: http://lxml.de/

sean
  • 3,955
  • 21
  • 28
0

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

Danish
  • 3,708
  • 5
  • 29
  • 48
0

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.

Community
  • 1
  • 1
Qanthelas
  • 514
  • 2
  • 8
  • 14
0

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)
Ervin
  • 706
  • 5
  • 21
0

For the people that intend to do the same thing but have difficulty with encoding, this was a generalized solution that changed an .xml with UTF-16 encoding.

It worked in python 2.7 modifying an .xml file named "b.xml" located in folder "a", where "a" was located in the "working folder" of python. It outputs the new modified file as "c.xml" in folder "a", without yielding encoding errors (for me) in further use outside of python 2.7.

file = io.open('a/b.xml', 'r', encoding='utf-16')
    lines = file.readlines()
    outFile = open('a/c.xml', 'w')
    for line in lines[0:len(lines)]:
        #replace author:
        pattern = '<Author>'
        subst = '    <Author>' + domain + '\\' + user_name + '</Author>'
        if pattern in line:
            line = subst
            print line

        outFile.writelines(line)
a.t.
  • 2,002
  • 3
  • 26
  • 66