Search This Blog

Simple Python Program to Write and read xml file

Simple Python Program to Write and read xml file
import os
import xml.dom.minidom

dirs = os.listdir()
ListofFileNames = []
for filename in dirs:
  print ("List of files : ",filename)
  ListofFileNames.append(filename)

print("Files Names : ",ListofFileNames)
print("Current Dir : ",os.getcwd())

filecomposite= open("Composite.xml","w+")
filecontent ='<note><to>Tove</to><from id="12345">Jani</from><heading>Reminder</heading><body>Don forget me this weekend!</body></note>'
filecomposite.write(filecontent)
filecomposite.close()

f=open("Composite.xml", "r")
if f.mode == 'r':
  contents =f.read()
  print (" File contents  :  ",contents)

def readxmltags():
  doc = xml.dom.minidom.parse("Composite.xml")
  elementValues = doc.getElementsByTagName("from")

 
  for elementvalue in elementValues:
        print("I am inside method - From element value : ",elementvalue.firstChild.data)
        attributeValue = elementvalue.getAttribute("id")
        print("Attribute values : ",attributeValue)
readxmltags()




Output :

List of files :  Composite.xml
List of files :  .bash_logout
List of files :  .profile
List of files :  .bashrc
List of files :  .pylint.d
List of files :  _test_runner.py
Files Names :  ['Composite.xml', '.bash_logout', '.profile', '.bashrc', '.pylint.d', '_test_runner.py']
Current Dir :  /home/runner
 File contents  :   <note><to>Tove</to><from id="12345">Jani</from><heading>Reminder</heading><body>Don forget me this weekend!</body></note>
I am inside method - From element value :  Jani
Attribute values :  12345

No comments:

Post a Comment