Solved

Read XML file using C#, limit and filter results

Posted on 2010-11-22
9
1,019 Views
Last Modified: 2012-05-10
Hi!

I am pretty new to .net
1. I want to read an XML file using C# and display data in web page.
2. I want to limit results to 10 records
3. I want to filter results using querystring

Here is what i have so far:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField HeaderText="Title" DataField="innerText" />
            </Columns>
        </asp:GridView>
     </div>
    </form> 
</body>
</html>

Open in new window

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    XmlDocument vidDocument = new XmlDocument();
    protected void Page_Load(object sender, EventArgs e)
    {
        vidDocument.Load(Server.MapPath("~/books.xml"));

        // this is how you get all the video nodes, perhaps to bind them or iterate over them
        XmlNodeList books = vidDocument.SelectNodes("/bookstore/book");

        // this would select all title elements
        XmlNodeList titles = vidDocument.GetElementsByTagName("title");

        // this binds the gridview to the title text to display
        GridView1.DataSource = titles;
        GridView1.DataBind();

    }

}

Open in new window

<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
	<book genre="autobiography">
		<title>The Autobiography of Benjamin Franklin</title>
		<author>
			<first-name>Benjamin</first-name>
			<last-name>Franklin</last-name>
		</author>
		<price>8.99</price>
	</book>
	<book genre="novel">
		<title>The Confidence Man</title>
		<author>
			<first-name>Herman</first-name>
			<last-name>Melville</last-name>
		</author>
		<price>11.99</price>
	</book>
	<book genre="philosophy">
		<title>The Gorgias</title>
		<author>
			<name>Plato</name>
		</author>
		<price>9.99</price>
	</book>
</bookstore>

Open in new window

0
Comment
Question by:kuzmar
  • 4
  • 3
  • 2
9 Comments
 
LVL 9

Accepted Solution

by:
abhinayp86 earned 375 total points
ID: 34192500
The best and easy way is to use LINQ to XML.

http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx
0
 
LVL 9

Assisted Solution

by:abhinayp86
abhinayp86 earned 375 total points
ID: 34192524
0
 
LVL 21

Expert Comment

by:masterpass
ID: 34192579
you can directly bind the xml to the gridview

http://msdn.microsoft.com/en-us/library/13ftcwy9%28VS.80%29.aspx

or

you can just load the sml file to dataset and SET the dataset as datasource of the gridview

http://msdn.microsoft.com/en-us/library/fx29c3yd.aspx
0
 

Author Comment

by:kuzmar
ID: 34192651
Sound quite interesting. But a bit too much for me.
I am really just starting with ASP.NET and do not know much about it.

Maybe some real example?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:abhinayp86
ID: 34192668
yeah.. Here is the working example for ur xml



protected void Page_Load(object sender, EventArgs e)

    {



        // Create the query 

        var custs = from c in XElement.Load(Server.MapPath("books.xml")).Descendants("title")

                    select c;



        // Execute the query 



        GridView1.DataSource = custs;

        GridView1.DataBind();



    }

Open in new window

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">  

            <Columns>  

                <asp:BoundField HeaderText="Title" DataField="value" />  

            </Columns>  

        </asp:GridView>  



    </div>

    </form>

</body>

</html>

Open in new window

0
 
LVL 21

Expert Comment

by:masterpass
ID: 34192673
Well, if you take a look at the links, it's both implemented through examples
0
 

Author Comment

by:kuzmar
ID: 34192695
This is great... but how do I limit results and filter for example by "price"?
0
 
LVL 21

Assisted Solution

by:masterpass
masterpass earned 125 total points
ID: 34192732
that is some thing that you can do in gridview.

gridview.allowPaging = true; // for limiting
gridview.pagesize = 10;

gridview.allowSorting = true; // for sorting

and you will need to write the events for both paging and sorting

these are complete list of events http://msdn.microsoft.com/en-us/library/hf8xwy0t.aspx

look for pageindexchanged and sorting events and implement them .
0
 
LVL 9

Assisted Solution

by:abhinayp86
abhinayp86 earned 375 total points
ID: 34192856
To limit the results, u need to use .Take(10)
Eg:

 var custs = (from c in XElement.Load(Server.MapPath("books.xml")).Descendants("title")  
                    select c).Take(10);  

And to sort, u need to use orderby

0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Duplicate a row 2 33
XSLT Help 12 20
Hide Tab Page 3 19
Iterate a dictionnary to change values 4 28
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now