First, we need to read our XML document into something that .NET can use.
This is very easy to do with the DataSet
object's ReadXml
method. By using
a DataSet
, we can treat our data like a database. Also, compared to using
the .NET XML objects, the DataSet
results in less code and complexity.
All we need to do is create a new DataSet and tell it to read our XML document into it:
DataSet dsProducts
=
new
DataSet
();
dsProducts
.
ReadXml
(
Server
.
MapPath
(
"productlist.xml"
));
The ReadXml
method is passed the file name of the XML file to read. This
example assumes that the file is named productlist.xml
and is located in the
same directory as the page using it.
Now that we have our data in a DataSet
, we need to be able to query it for
an SKU
and return the Price
and Description
for the corresponding product.
To do this, we will use a DataView
object:
DataView dvProducts
=
new
DataView
(
dsProducts
.
Tables
[
"Products"
]);
dvProducts
.
Sort
=
"SKU"
;
The DataView
is created by passing the constructor a DataTable
, "Products", in our DataSet
. After we create the DataView
, we need to sort it. Since we
are using the SKU
as the lookup value, we need to sort on it. This is
similar to an index or primary key in a database. If we don't sort the
DataView, we will get a runtime error when we try to use it's Find
method.
With our DataView
sorted, use the Find
method to return only the row(s)
which match the SKU
we give it. In this example, we want to return the
Price
and Description
for a product with a SKU
equal to 1:
int
rowIndex
=
dvProducts
.
Find
(
"1"
);
string
Price
,
Description
;
if
(
rowIndex
== -
1
)
{
// The SKU was not found in our data
Response.Write("SKU not found");
}
else
{
Price=dvProducts[rowIndex]["Price"].ToString();
Response.Write("Price: "+Price+"<br>";
// Price: 100.00
Description=dvProducts[rowIndex]["Description"].ToString();
Response.Write("Description: "+Description);
// Description: Widget #1
}
The Find
method of a DataView
returns and int which is the index of the row
in the DataView
containing the sort key value passed to it. If there is no
match, it returns -1.
Comments