Reputation: 77
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?
Upvotes: 1
Views: 306
Reputation: 2779
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)
Upvotes: 0
Reputation: 746
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)
Upvotes: 0
Reputation: 142256
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>
Upvotes: 2
Reputation: 524
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.
Upvotes: 0
Reputation: 3798
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
Upvotes: 0
Reputation: 3985
As with all the other XML questions on here for python look at lxml
Link: http://lxml.de/
Upvotes: 1