Mega Code Archive

 
Categories / C# Tutorial / XML
 

Using XPath to filter data from Database

using System; using System.Data; using System.Data.SqlClient; using System.Xml; using System.IO; public class XPathSearch {     private static string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";     public static void Main()      {         string SQL = "SELECT CategoryID, CategoryName, Description FROM Categories";         SqlConnection con = new SqlConnection(connectionString);         SqlCommand com = new SqlCommand(SQL, con);         SqlDataAdapter adapter = new SqlDataAdapter(com);         DataSet ds = new DataSet("Northwind");         con.Open();         adapter.FillSchema(ds, SchemaType.Mapped, "Categories");         adapter.Fill(ds, "Categories");         con.Close();         XmlDataDocument dataDoc = new XmlDataDocument(ds);         string XPath;         XPath = @"//Categories[starts-with(child::CategoryName, 'A')]";         XmlNodeList nodes = dataDoc.DocumentElement.SelectNodes(XPath);         foreach (XmlNode node in nodes)         {             foreach (XmlNode child in node.ChildNodes)             {                 Console.WriteLine(child.InnerText);             }          }     } }