Searching an XML File

If you’ve ever wondered how to search an XML file, like you would a regular database, this sample is for you. We start with an XML file called ‘cars.xml’. The rest, though, is code, not history :)

You can download the xml file here.

<%@ Import Namespace="System.Data" %>

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim ds as DataSet = new DataSet()
	ds.ReadXml(Server.MapPath("/data/cars.xml"))
	ddlPrice.DataSource=ds
	ddlPrice.DataTextField="Price"
	ddlPrice.DataBind
end if
End Sub

Sub GetCar(Source as Object, E as EventArgs)
	Dim dsProducts as DataSet = new DataSet()
	dsProducts.ReadXml(Server.MapPath("/data/cars.xml"))
	Dim dv as DataView = new DataView(dsProducts.Tables("Products"))
	dv.Sort = "Price"
	Dim rowIndex as integer = dv.Find(ddlPrice.SelectedItem.Text)
	Dim Price, Vehicle as String

if (rowIndex = -1) Then
	Response.Write("Car not found")
else
	ph1.visible="True"
	Price = dv(rowIndex)("Price").ToString()
	lblPrice.text = "Price: " + FormatCurrency(Price) + "<br>"
	Vehicle = dv(rowIndex)("Vehicle").ToString()
	lblCar.text="Vehicle : " + Vehicle
End If
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Searching an XML File</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlPrice" Runat="server"/>
<asp:Button id="button1"
	Text="Get Car"
	onclick="GetCar"
	Runat="server" /><br>
<asp:placeholder ID="ph1" Visible="False" Runat="server">
<asp:Label ID="lblCar" Runat="server" /> --
<asp:Label ID="lblPrice" Runat="server" /><br>
</asp:placeholder>
</form>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>