XML parsing in Python3 (working with ElementTree)

XML Parsing in Python3

XML :

XML stands for the eXtensible Markup Language. It was designed for data transport and data storage. It was designed for both Human and machine readable.

That's enough for the introduction.
Let's start working.


post logo
First of all the XML file that we are working on.

<messages>
  <note id="501">
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>This is code in cafe</body>
  </note>
  <note id="502">
    <to>Jani</to>
    <from>Tove</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note>
</messages>

We are using this file as an example XML file, name this file as the "example.xml".

Let's start working with the python3.


to Parse the XML by the python first, we have to import a module named 

xml.etree.ElementTree


import xml.etree.ElementTree as ET 
d = ET.parse("example.xml").getroot()

getroot() returns the root node of the XML data.
you can also use the ET.fromstring(xml_data_string)

now we have XML parsed and stored in the variable, let's get data from it.

suppose we want to get the body of all the notes then sample code is.


for i in d.findall("note"):
print(i.find("body").text)

this chunk of code gives us the all the body tag values in the print.

whole working code summed up into one.



import xml.etree.ElementTree as ET 

#parse return a handle
#getroot return a root tag of the whole xml
d = ET.parse("example.xml").getroot()

#findall iterate through all the iteration of the particular tag.
for i in d.findall("note"):
#find checks the single iter of the tag
print(i.find("body").text)

#repeating the process again
for i in d.findall("note"):
#formatting the message again
print("Message from "+i.find("from").text + " to "+ i.find("to").text )

And the sample output for this code is 


output
working with the XML is easy very easy.

For more tutorials and tips stay tuned to our blog.

if you have any query or suggestion please feel free to share them in the comment box below. or if have a question then ask me in the comment section.
If you have liked this then please give us some love and share it with your friends.
Thanks for being here.

Comments

Popular posts from this blog

Third Equation of motion, How to implement using C language

Second Equation of motion, How to implement using C language

First Equation of motion, How to implement using C language