Reading XML file nodes as key value pair using C#

Problem Statement: we have an XML file and it has a set of keys and values we have to read it using C#

XML Look like this :

       

<?xml version="1.0" encoding="UTF-8"?>

<root>

<bangalore>

<item key="madiwala" value="56043" />

<item key="whitefield" value="56048" />

<item key="hebbal" value="56050" />

</bangalore>

</root>


Solution: We will use System.Xml library in the dot net framework to load the file and then we will select the specific node we want and loop all the item from it and we will add to a dictionary as key-value pair.



so here you can check the code for the same.











       
 //Loading Xml

  string xmlPath = @"C:\Tony\Location.xml"

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(xmlPath);



  // Getting Node

            XmlNodeList locationDetails = xmlCountryDocument.SelectNodes("root/bangalore");

            Dictionary<string, string> dicPlacePinXml = new Dictionary<string, string>();

   

   //Looping

            foreach (XmlNode locationNode in locationDetails)

            {


               foreach (XmlNode elementLoc in locationNode.ChildNodes)

                {

                    dicPlacePinXml.Add(elementLoc.Attributes["key"].Value, elementLoc.Attributes["value"].Value);
                }

            }

So here our "dicPlacePinXml" variable will be having the place and pin as key-value pair.
/* androidsharp */

0 comments: