-1
<inboundContextData>
 <items>
    <item>
        <key>a</key>
        <value>One</value>
    </item>
    <item>
        <key>b</key>
        <value>Two</value>
    </item>
    <item>
        <key>c</key>
        <value>Three</value>
    </item>
 </items>
</inboundContextData>

I have to replace the values One, Two and Three with some other number using the python script. Please suggest what needs to done

mzjn
  • 48,958
  • 13
  • 128
  • 248
  • Possible duplicate of this: https://stackoverflow.com/questions/6523886/find-and-replace-values-in-xml-using-python – ColdMeteor Jul 19 '18 at 17:26
  • The question is tagged "python", but there is no Python code. Please take some time to research the problem. Surely you have tried something yourself? – mzjn Jul 19 '18 at 17:30

3 Answers3

0

For manipulating XML document you can use BeautifulSoup package. Example:

data = """
<inboundContextData>
<items>
    <item>
        <key>a</key>
        <value>One</value>
    </item>
    <item>
        <key>b</key>
        <value>Two</value>
    </item>
    <item>
        <key>c</key>
        <value>Three</value>
    </item>
</items>"""


from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'xml')

my_new_value = 'XXX'

for value in soup.select('items > item > value'):
    value.clear()
    value.append(my_new_value)

print(soup.prettify())

Output:

<?xml version="1.0" encoding="utf-8"?>
<inboundContextData>
 <items>
  <item>
   <key>
    a
   </key>
   <value>
    XXX
   </value>
  </item>
  <item>
   <key>
    b
   </key>
   <value>
    XXX
   </value>
  </item>
  <item>
   <key>
    c
   </key>
   <value>
    XXX
   </value>
  </item>
 </items>
</inboundContextData>
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Using ElementTree

Demo:

import xml.etree.ElementTree
et = xml.etree.ElementTree.parse(filename)
root = et.getroot()
for i in root.findall("item"):
    i.find("value").text = "NewNumber"

et.write(filename)

Output:

<items>
    <item>
        <key>a</key>
        <value>NewNumber</value>
    </item>
    <item>
        <key>b</key>
        <value>NewNumber</value>
    </item>
    <item>
        <key>c</key>
        <value>NewNumber</value>
    </item>
</items>
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can use the ElementTree. With this you can load xml into a multidimensional list where you can access the elements hierarchically. For example, starting from root you xml can see as:

<inboundContextData> <- root
<items> root <- 0
    <item> root <- 0 <- 0
        <key>a</key>
        <value>One</value> root <-0 <-0<-1
    </item>
    <item>
        <key>b</key>
        <value>Two</value>
    </item>
    <item>
        <key>c</key>
        <value>Three</value>
    </item>
</items>

So, to alter the first "value" you would do so:

from xml.etree import ElementTree as ET

xml = ET.parse('testfile.xml')
root = xml.getroot()

root[0][0][1].text = 'Five'

xml.write('testfile.xml')
Eduardo Soares
  • 992
  • 4
  • 14