Saturday, July 13, 2013

Reading Selected Elements from XML

place.xml
-----------
<?xml version="1.0" encoding="utf-8" ?>
<Places>
  <Place>
    <Id> 1 </Id>
    <City>Chennai</City>
    <Country>INDIA </Country>
  </Place>
  <Place>
    <Id> 2 </Id>
    <City> Atlanta </City>
    <Country>USA </Country>
  </Place>
</Places>
Default.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="XML_Default8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
   <head id="Head1" runat="server">
   <title>Reading XML</title>
   </head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="ddl" runat="server"></asp:DropDownList>&nbsp;<br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
    <asp:GridView ID="grxml" runat="server">
    </asp:GridView>  
    </form>
</body>
</html>
Default.aspx.cs
----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
using System.Text;
public partial class XML_Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/place.xml"));
            XmlNodeList bookList = doc.GetElementsByTagName("Place");
            foreach (XmlNode node in bookList)
            {
                XmlElement bookElement = (XmlElement)node;
                string ctry = bookElement.GetElementsByTagName("Country")[0].InnerText;
                ddl.Items.Add(ctry);
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Id");
        DataColumn dc1 = new DataColumn("City");
        dt.Columns.Add(dc);
        dt.Columns.Add(dc1);
        string ct = ddl.SelectedItem.ToString();
        string dataPath = Server.MapPath("~/place.xml");
        DataSet dSet = new DataSet();
        dSet.ReadXml(dataPath);
        DataRow[] rows = dSet.Tables[0].Select(" Country = '" + ct + "'");
        foreach (DataRow dr in rows)
        {
            DataRow myRow = dt.NewRow();
            myRow["Id"] = dr["Id"];
            myRow["City"] = dr["City"];
            dt.Rows.Add(myRow);
        }
        grxml.DataSource = dt;
        grxml.DataBind();
    }
}

Read XML Data Into DataSet In Asp.Net C# VB.NET

using System.Data;
using System.IO;
protected void btnReadXmlFile_Click(object sender, EventArgs e)
    {
        string filePath = Server.MapPath("~/Employees.xml");
        DataSet dsData = new DataSet();
        //If you don't want to read through FileStream then comment below line
        FileStream fsReadSchema = new FileStream(filePath, FileMode.Open);
        dsData.ReadXml(fsReadSchema);
        fsReadSchema.Close();
        GridView1.DataSource = dsData;
        GridView1.DataBind();
    }

HOW TO: Read an XML file in ASP.NET/C#

 
XML is used almost everywhere these days to facilitate sharing data between applications, between application layers or simply as data storage. This post shows you a basic method of reading an XML file in ASP.NET and display the output on an .aspx page. We will take the following xml as an example that has information about book such as title, ISBN, and author.


<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book>
    <Title>Programming Microsoft ASP.NET 4</Title>
    <ISBN>9780735643383</ISBN>
    <Author>Dino Esposito</Author>
  </Book>
  <Book>
    <Title>Microsoft Visual C# 2010 Step by Step</Title>
    <ISBN>0735626707</ISBN>
    <Author>John Sharp</Author>
  </Book>
  <Book>
    <Title>Programming Microsoft ADO.NET Core Reference</Title>
    <ISBN>073562206X</ISBN>
    <Author>David Sceppa</Author>
  </Book>
</Books>


Here is the C# code to read the above XML file which is stored in the root application folder in the attached example and display the data on the asp.net page.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
using System.Text;
public partial class Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind Data to Gridview
            readXML();
        }
    }
    // This method is used to get xml node values and bind to gridview
    private void readXML()
    {
        XmlDocument doc = new XmlDocument();
        //Load XML from the file into XmlDocument object
        doc.Load(Server.MapPath("~/SampleXML.xml"));
        XmlNode root = doc.DocumentElement;
        StringBuilder sb = new StringBuilder();
	//Select all nodes with the tag Book
        XmlNodeList nodeList = root.SelectNodes("Book");
	//Loop through each node under the node “Book”
        foreach (XmlNode node in nodeList)
        {
            sb.Append("Title: ");
	    //Select the text from a single node, “Title” in this case
            sb.Append(node.SelectSingleNode("Title").InnerText);
            sb.Append("ISBN: ");
            sb.Append(node.SelectSingleNode("ISBN").InnerText);
            sb.Append("Author: ");
            sb.Append(node.SelectSingleNode("Author").InnerText);
            sb.Append("");
        }
        Response.Write(sb.ToString());
    }
}

Asp.net Read xml node values and bind data to gridview

SampleXML.xml
----------------
<?xml version="1.0" encoding="utf-8" ?>
<users>
  <user>
    <FirstName>FName1</FirstName>
    <LastName>LName1</LastName>
    <UserName>Names</UserName>
    <Job>
      <Role>SE</Role>
    </Job>
  </user>
  <user>
    <FirstName>FName1</FirstName>
    <LastName>LName1</LastName>
    <UserName>Names</UserName>
    <Job>
      <Role>SOftware Developer</Role>
    </Job>
  </user>
  <user>
    <FirstName>FName1</FirstName>
    <LastName>LName1</LastName>
    <UserName>Names</UserName>
    <Job>
      <Role>SE</Role>
    </Job>
  </user>
</users>
Default.aspx
------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="XML_Default8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Read XML Node values and bind data to gridview</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvDetails" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</form>
</body>
</html>
Default.aspx.cs
------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
public partial class XML_Default8 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind Data to Gridview
            GetXMLData();
        }
    }
    // This method is used to get xml node values and bind to gridview
    protected void GetXMLData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("FirstName", typeof(string));
        dt.Columns.Add("LastName", typeof(string));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Role", typeof(string));
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("~/SampleXML.xml"));
        XmlNodeList nodeList = xmldoc.SelectNodes("/users/user");
        foreach (XmlNode node in nodeList)
        {
            DataRow dtrow = dt.NewRow();
            dtrow["FirstName"] = node["FirstName"].InnerText;
            dtrow["LastName"] = node["LastName"].InnerText;
            dtrow["UserName"] = node["UserName"].InnerText;
            dtrow["Role"] = node["Job"]["Role"].InnerText;
            dt.Rows.Add(dtrow);
        }
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }
}

How to read and process Xml file element data in asp.net

ITBookStore.xml
-----------------
<?xml version="1.0" encoding="utf-8" ?>
<!-- This is a sample XML file for various XML example-->
<books>
  <book ID="1">
    <name>Adobe Flex 3: Training from the Source</name>
    <author>Jeff Tapper</author>
    <price>47.99</price>
    <type>Flex</type>
    <image>AdobeFlex3.jpeg</image>
  </book>
  <book ID="2">
    <name>Styling Web Pages with CSS</name>
    <author>Tom Negrino</author>
    <price>15.99</price>
    <type>CSS</type>
    <image>CSS.jpeg</image>
  </book>
  <book ID="3">
    <name>Adobe Flash CS4 Professional</name>
    <author>Mark Schaeffer</author>
    <price>19.99</price>
    <type>Flash</type>
    <image>FlashCS4.jpeg</image>
  </book>
</books>
Default.aspx
-----------------
<%@ Page Language="C#" %>  
<%@ Import Namespace="System.Xml" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  
<script runat="server">  
    protected void Page_Load(object sender, System.EventArgs e)  
    {
        string xmlFile = Request.PhysicalApplicationPath + @"ITBookStore.xml";   //App_Data\ITBookStore.xml
        XmlReaderSettings settings = new XmlReaderSettings();  
        settings.IgnoreComments = true;  
        settings.IgnoreWhitespace = true;  
        try  
        {  
            using (XmlReader reader = XmlReader.Create(xmlFile, settings))  
            {  
                string xmlContent;  
                while (reader.Read())  
                {  
                    if (reader.NodeType == XmlNodeType.Element)  
                    {  
                        xmlContent = "";  
                        if (reader.Name == "name")  
                        {  
                            xmlContent += "Book: " + reader.ReadString().ToString() + "<br />";  
                        }  
                        if (reader.Name == "author")  
                        {  
                            xmlContent += "Author: " + reader.ReadString().ToString() + "<br />";  
                        }  
                        if(reader.Name == "price")  
                        {  
                            xmlContent += "Price: $" + reader.ReadString().ToString() + "<br />";  
                        }  
                        if(reader.Name == "type")  
                        {  
                            xmlContent += "Type: " + reader.ReadString().ToString() + "<br />";  
                        }  
                        if(reader.Name == "image")  
                        {  
                            xmlContent += "Image: " + reader.ReadString().ToString() + "<br /><br />";  
                        }  
                        Label1.Text += xmlContent;  
                    }  
                }  
            }  
        }  
        catch (Exception ex)  
        {  
            Label1.Text = "An Error Occured: " + ex.Message;  
        }  
    }  
</script>  
  
<html xmlns="http://www.w3.org/1999/xhtml" >  
<head id="Head1" runat="server">  
    <title>XmlReader: How to read and process Xml file element data in asp.net</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:Navy; font-style:italic;">XML Example: Reading Xml Element Data</h2>  
        <asp:Label   
             ID="Label1"  
             runat="server"  
             Font-Bold="false"  
             ForeColor="Crimson"  
             Font-Size="Large"  
             Font-Names="Comic Sans MS"  
             >  
        </asp:Label>  
    </div>  
    </form>  
</body>  
</html>