Search Xml data using a Primary key

Ddd
Posted by Ddd under C# category on | Points: 40 | Views : 2563
//Search Xml data using a Primary key

//This is the Xml file known as data.xml. save it in the C drive

<?xml version="1.0" encoding="utf-8" ?>
<catalog>
<book bookid="b001">
<bookname>ASP.NET</bookname>
<publisher>APRESS</publisher>
</book>
<book bookid="b002">
<bookname>UNIX</bookname>
<publisher>ABC PRESS</publisher>

</book>
</catalog>

//The code is in the Main() method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//add this namespace
using System.Data;

namespace ConsoleApplication20jan
{
class Class3
{

static void Main()
{
DataSet ds = new DataSet();
ds.ReadXml("c:\\data.xml");
//define the primary key
DataColumn[] dc = new DataColumn[1];
dc[0] = ds.Tables[0].Columns["bookid"];

ds.Tables[0].PrimaryKey = dc;

//search using the Primary key
Console.WriteLine("enter bookid");
string s=Console.ReadLine();
DataRow dr = ds.Tables[0].Rows.Find(s);
if (dr == null)
{
Console.WriteLine("wrong bookid");
}
else
{
Console.WriteLine("bookname" + "---" + dr["bookname"]);
Console.WriteLine("publisher" + "---" + dr["publisher"]);

}

}
}
}

Comments or Responses

Login to post response