Saturday 22 March 2014

read xml xmlreader c#

XmlReader  parses XML files. It read attribute of XML values, text nodes and multiple tags names. XMLReader is more complex to implement  than other solutions but it provides performance.
@XML Sample      
xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee name="Bob">
    788787878778
  </Employee>
  <Employee name="jhon">
   uyuyuyyy
  </Employee>
</Employees>                     
@Code Snippet to read XML file by XMLReader in c#;
///
        /// Main method
        ///
        ///
        public static void Main(String[] args)
        {
            // Create an XML reader for this file.
            using (XmlReader reader = XmlReader.Create("E:\\Employee.xml"))
            {
                while (reader.Read())
                {
                    // Only detect start elements.
                    if (reader.IsStartElement())
                    {
                        // Get element name and switch on it.
                        switch (reader.Name)
                        {
                            case "Employees":
                                // Detect this element.
                                Console.WriteLine("Start element.");
                                break;
                            case "Employee":
                                // Detect this article element.
                                Console.WriteLine("Start element.");
                                // Search for the attribute name on this current node.
                                string attribute = reader["name"];
                                if (attribute != null)
                                {
                                    Console.WriteLine("  Has attribute ame: " + attribute);
                                }
                                // Next read will contain text.
                                if (reader.Read())
                                {
                                    Console.WriteLine("  Text node Number: " + reader.Value.Trim());
                                }
                                break;
                        }
                    }
                }
            }
        }
@OutPut

No comments:

Post a Comment