0

Below is the example xml file.

    <?xml version='1.0' encoding='UTF-8'?>
    <a>
        <b>
            <c>
                <d>TEXT</d>
            </c>  
       </b>
    </a>

I need to Replace "TEXT" with list of strings so that my xml look like below.

    <?xml version='1.0' encoding='UTF-8'?>
    <a>
        <b>
            <c>
                <d>TEXT1,TEXT2,TEXT3</d>
            </c>  
       </b>
    </a>

Please tell me how can i achieve this using python.

2

4 Answers 4

0

this should work,

from xml.dom import minidom
doc = minidom.parse('my_xml.xml')
item = doc.getElementsByTagName('d')
print item[0].firstChild.nodeValue
item[0].firstChild.replaceWholeText('TEXT, TEXT1 , etc...')

for s in item: #if you want to loop try this
    s.firstChild.replaceWholeText('TEXT, TEXT1 , etc...')
Sign up to request clarification or add additional context in comments.

Comments

0

You can use lxml but it depends on your actual purpose of use, here is an example:

from lxml import etree

a = '''<?xml version='1.0' encoding='UTF-8'?>
<a>
    <b>
        <c>
            <d>TEXT</d>
        </c>  
   </b>
</a>'''

tree = etree.fromstring(a)
#for file you need to use tree = etree.parse(filename)
for item in tree:
    for data in item:
        for point in data:
            if point.tag == 'd':
                if point.text == 'TEXT':
                    point.text = 'TEXT,TEXT,TEXT'
print(etree.tostring(tree))
#<a>
#    <b>
#        <c>
#            <d>TEXT,TEXT,TEXT</d>
#        </c>  
#   </b>
#</a>

Comments

0

You can treat an xml file just as a text file and use the functions you would use to manipulate strings. For example:

with open('testxml.xml','r') as f:
    contents=f.read() #open xml file

stringlist=['Text1','Text2','Text3'] #list of strings you want to replace with
opentag='<d>' #tag in which you want to replace text
closetag='</d>'

oldtext=contents[contents.find(opentag)+3:contents.find(closetag)] 
newtext=''.join(str_+',' for str_ in stringlist)[:-1] #ignore last comma
contents=contents.replace(oldtext,newtext) #replace old text with new

with open('testxml.xml','w') as f:
    f.write(contents) #write contents to file

There might be many instances where you have a lot of nested tags and this simple script would not work. You could use Python's built in XML editing package ElementTree if you want to do more advanced tasks.

Comments

0

Try this:

a = a.replace(<old string>, <new string>)

read file and do this operation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.