Python Forum

Full Version: Replace XML tag and write to the same file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have a xml file with name "binary.xml" with below contents- Need to replace the value of tag identity from ABCDEFG to some new value e.g. 123456. When I'm trying to replace using re file is getting over written. Can you help with a snippet?

<config version="v1"> 
    <chain template="file-system">                            // Use the “”file-system” template
    <provider id="file-system" type="file-system">            // Modify the “file-system” binary provider
        <fileStoreDir>$FILESTORE/binaries</fileStoreDir>    // Override the <fileStoreDir> attribute
    </provider>
    <provider>
      <identity>ABCDEFG</identity>
      <endpoint>some point.com</endpoint>
    </provider>
</config>
Please show what you have tried so far.
Use BS-4 find the tag then use string.replace_with.
from bs4 import BeautifulSoup

xml = '''\
<provider>
  <identity>ABCDEFG</identity>
  <endpoint>some point.com</endpoint>
</provider>'''

soup = BeautifulSoup(xml, 'xml')
>>> result = soup.find('identity')
>>> result.string.replace_with('123456')

>>> soup
<?xml version="1.0" encoding="utf-8"?>
<provider>
<identity>123456</identity>
<endpoint>some point.com</endpoint>
</provider>
Thanks Larz60+ & Snippsat. I'm able to pass through and new file is being generated with below code but this is deleting the comments which are already there in source xml file. Any thoughts on how to get the comments as well to the new file ?

import xml.etree.ElementTree as ET

def newidentity(filename):
   tree = ET.ElementTree(file=filename)
   root = tree.getroot()
   for id in root.iter('identity'):
       print id.text
       identity.text = "123456"
       tree = ET.ElementTree(root)
       print tree
   with open("newfile.xml", "wb") as somefile:
      tree.write(somefile)

if __name__ == "__main__":
   newidentity(filename)
I helped before with ElementTree,but now i do not touch it.
As i have spend unnecessary time to fix stuff in ElementTree,that eg BS-4 or lxml do right.
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('binary.xml', encoding='utf-8'), 'xml')
result = soup.find('identity')
result.string.replace_with('123456')
with open('out.xml', 'w', encoding='utf-8') as f:
    f.write(str(soup))
Now get a validat .xml file back where only wanted change is made.
if want file overwritten give same name when write binary.xml,that will also work.
Output:
<?xml version="1.0" encoding="utf-8"?> <config version="v1"> <chain template="file-system"> // Use the “”file-system” template <provider id="file-system" type="file-system"> // Modify the “file-system” binary provider <fileStoreDir>$FILESTORE/binaries</fileStoreDir> // Override the <fileStoreDir> attribute </fileStoreDir> <provider> <identity>123456</identity> <endpoint>some point.com</endpoint> </provider> </provider></chain></config>