Saturday 22 March 2014

how to read xml file in c#

There are many ways to read the XML file like XMLReader , XMLTestReader, XMLDocument.
Read XML file using  XMLDocument

Suppose you have the XML as
<Employee>
  <employe>
    <Name>John</Name>
    <phonenumber>787887878</phonenumber>
  </employe>
  <employe>
    <Name>Jane</Name>
    <phonenumber>7867678676</phonenumber>
  </employe>
</Employee>


loop through the collection of employee from  each of employe  retrieve its first and phone number;



@Code snippet
   class Program
    {
        ///
        /// Main method
        ///

        ///
        public static void Main(String[] args)
        {
            Program _app = new Program();
            // Passing XML text as a String, you can also use the
            // XMLDocument::Load( ) method to read the XML from a file.
            //
            _app.ProcessXML(@"
 
    John
    787887878
 

 
    Jane
    7867678676
 

");
        }
        //Call method to print the values
        public void printValue(String strName, String strPhoneNumber)
        {
            Console.WriteLine("{0} - {1}", strName, strPhoneNumber);
        }
        //Process the XML values
        public void ProcessXML(String xmlText)
        {
            XmlDocument _doc = new XmlDocument();
            _doc.LoadXml(xmlText);
            //  _doc.Load( _strFilename); //alternat way to read from a file.
            XmlNodeList _Name = _doc.GetElementsByTagName("Name"); //Name is name of node
            XmlNodeList _phoneNumber = _doc.GetElementsByTagName("phonenumber");
            
            for (int _i = 0; _i < _Name.Count; ++_i)
            {
                printValue(_Name[_i].InnerText,
                    _phoneNumber[_i].InnerText);
            }
        }
    }


@output

No comments:

Post a Comment