Solved

Read XML file using C#, limit and filter results

Posted on 2010-11-22
9
1,024 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Registering DLL 5 43
Allow space in this pattern 2 46
MS Access XML API HTTP POST Call Object Send Not Working Correctly 15 33
Run time Error 4 34
Many times as a report developer I've been asked to display normalized data such as three rows with values Jack, Joe, and Bob as a single comma-separated string such as 'Jack, Joe, Bob', and vice versa.  Here's how to do it. 
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
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…
Delivering innovative fully-managed cloud services for mission-critical applications requires expertise in multiple areas plus vision and commitment. Meet a few of the people behind the quality services of Concerto.

947 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

23 Experts available now in Live!

Get 1:1 Help Now