Solved

Read XML file using C#, limit and filter results

Posted on 2010-11-22
9
1,048 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

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
 
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

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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. 
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

751 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