Python Parse XML

Below code shows how to parse an XML document in Python.

XML document simplexml.xml
<?xml version="1.0" encoding="UTF-8" ?>
<person>
  <firstname>Joe</firstname>
  <lastname>Marini</lastname>
  <home>Seattle</home>
  <skill name="JavaScript"/>
  <skill name="Python"/>
  <skill name="C#"/>
  <skill name="HTML"/>
</person>



Python XML parser code
# 
# Python parse xml
#

import xml.dom.minidom

def main():
  # use the parse() function to load and parse an XML file
  doc = xml.dom.minidom.parse("samplexml.xml")
  
  # print out the document node and the name of the first child tag
  print(doc.nodeName)
  print(doc.firstChild.tagName)
  
  # get a list of XML tags from the document and print each one
  skills = doc.getElementsByTagName("skill")
  print("%d skills: " % skills.length)
  for skill in skills:
    print(skill.getAttribute("name"))
    
  # create a new XML tag and add it into the document
  newSkill = doc.createElement("skill")
  newSkill.setAttribute("name", "Java")
  doc.firstChild.appendChild(newSkill)

  print("-------------------------------")
  #After adding new skill
  # get a list of XML tags from the document and print each one
  skills = doc.getElementsByTagName("skill")
  print("%d skills: " % skills.length)
  for skill in skills:
    print(skill.getAttribute("name"))


if __name__ == "__main__":
  main();



-------------------------------------------------------
#Output

#document
person
4 skills:
JavaScript
Python
C#
HTML
-------------------------------
5 skills:
JavaScript
Python
C#
HTML
Java

Comments

Popular posts from this blog

How to write to a file in Kotlin

Python Tkinter example