Menu ▼

Home / blogs / Dotnet / XML /

This example shows you how to read xml file node value in c#. By using XmlDocument we can load xml file(xml.Load(xmlfilepath)) or xml string(xml.LoadXml(xmlstring)), then xml.SelectNodes() will return the XmlNodeList. foreach of XmlNodeList will run loop on each XmlNode and XmlNod[NodeName].InnerText will return the value of the node.

Input XML Strin

private string GetXML()
{
    return @"<?xml version='1.0' encoding='UTF-8' ?>
    <EmployeeList>
        <Employee>
        <Name>James</Name>
        <DOJ>10/05/2014</DOJ>
        </Employee>
        <Employee>
        <Name>Smith</Name>
        <DOJ>06/03/2013</DOJ>
        </Employee>
        <Employee>
        <Name>Williams</Name>
        <DOJ>02/01/2013</DOJ>
        </Employee>
    </EmployeeList>";
}

Reading XML value

protected void Page_Load(object sender, EventArgs e)
{
    string strXML = GetXML();

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(strXML);

    XmlNodeList xNodeList = xml.SelectNodes("/EmployeeList/Employee");
    foreach (XmlNode xNode in xNodeList)
    {
        string employeeName = xNode["Name"].InnerText;
        string DOJ = xNode["DOJ"].InnerText;
        Response.Write("Employee Name: " + employeeName + "<br/>DOJ: " + DOJ + "<br/><br/>");
    }
}

Output
reading xml using c#

Read More...
Submited By : mrkraju On 13 Dec 2015
The below code will convert the XML of countries and its cities to dataset.

        string xmlstring =

                    @"<countries>

                      <country name='India'>

                        <city>Delhi</city>

                        <city>Mumbai</city>

                        <city>Hyderabad</city>

                      </country>

                      <country name='Australia'>

                        <city>Sydney</city>

                        <city>Hobart</city>

                        <city>Canberra</city>

                      </country>

                      <country name='Canada'>

                        <city>Toronto</city>

                        <city>Niagara</city>

                        <city>Victoria</city>

                      </country>

                      <country name='USA'>

                        <city>Dallas</city>

                        <city>Washington</city>

                        <city>Chicago</city>

                      </country>

                    </countries>";

         System.Data.DataSet ds = new System.Data.DataSet();

        ds.ReadXml(new System.IO.StringReader(xmlstring));


Output DataSet :





Read More...
Submited By : mrkraju On 08 Nov 2013




Search dotnetlearners.com