I have this XML code and I want to print value of UserName and Email on console.Can you help me??

<?xml version="1.0"?>
<USERS>
  <User>
    <UserName>abc</UserName>
    <Email>abc@gmail.com</Email>
  </User>
  <User>
    <UserName>abc</UserName>
    <Email>abc@gmail.com</Email>
  </User>
  <User>
    <UserName>abc</UserName>
    <Email>abc@gmail.com</Email>
  </User>
  <User>
    <UserName>abc</UserName>
    <Email>abc@gmail.com</Email>
  </User>  
</USERS>

Use XmlDocument class to read data.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\myXml.xml");

There are many ways you can display, basically you'll have to navigate through the aquired data. One easy way would be to put all the nodes of the XmlDocument object to an XmlNodeList.

XmlNodeList nodeList = xmlDoc.ChildNodes;

You can write a recursive function as follows to get the data from your XML file. However remember that it suits ONLY for your XML file, and if the structure changes the funcion too will have to be changed.

private void Display(XmlNodeList nodeList)
        {
            foreach (XmlNode node in nodeList)
            {
                if (node.Name == "UserName" || node.Name == "Email")
                {
                    Console.WriteLine(node.Name + " = " + node.FirstChild.Value + "\r\n");
                }
                else
                {
                    Display(node.ChildNodes);
                }
            }
        }

Edited 6 Years Ago by sachintha81: n/a

Have you tried DataSet.ReadXml(); ? It will automatically create a dataset with a datable that you can use to databind to a control, or just enumerate, search, edit, and of course it has a matching SaveXml() method that creates an XML.

This article has been dead for over six months. Start a new discussion instead.