This code Shows how to search for a particular element (other than root element) in the XML File and display them in the Gridview.I enter the word to search for in the TextBox named TextBox1 and below is the XML File.
If i give book in the textbox all the bid and authors will be displayed in the grid..similarly u can search for bid and authors too. NOTE: Replace < and > with [ and ]
[?xml version="1.0" encoding="utf-8" ?] [books] [book] [bid]B001[/bid] [author]James[/author] [/book] [book] [bid]B002[/bid] [author]Steven[/author] [/book] [book] [bid]B003[/bid] [author]John[/author] [/book] [book] [bid]B004[/bid] [author]Iris[/author] [/book] [/books]
The coding for this is
protected void Button1_Click(object sender, EventArgs e) {
XmlTextReader Xreader = new XmlTextReader(HttpContext.Current.Server.MapPath("country.xml")); Xreader.WhitespaceHandling = WhitespaceHandling.None; XmlDocument Xdoc = new XmlDocument(); Xdoc.Load(Xreader); XmlNode Xnode = Xdoc.DocumentElement; if (TextBox1.Text != Xnode.Name.ToString()) { AddCountry(Xnode, 1); DataTable finaldt = new DataTable(); finaldt = (DataTable)Session["dt"]; GridView gv = new GridView(); gv.DataSource = finaldt; gv.DataBind(); gv.Visible = true; PlaceHolder1.Controls.Add(gv); Session["dt"] = null; } else { TextBox1.Text = "Cannot search by root element"; } } int cnt; private void AddCountry(XmlNode Xnode, Int32 intlevel) { XmlNode Xnodeworking; int rows = 0; DataTable dt = new DataTable(); if (Session["dt"] !=null) { dt = (DataTable)Session["dt"]; } DataRow dr = dt.NewRow(); String strindent = new string(' ', 2 * intlevel); string strvalue = (string)Xnode.Value; if (strvalue != null) { strvalue = " : " + strvalue; } if (Xnode.Name == TextBox1.Text.ToString()) { if (Xnode.NodeType == XmlNodeType.Element) { XmlNodeList mapattributes = Xnode.ChildNodes; if (cnt != 1) { foreach (XmlNode xnodattribute in mapattributes) { dt.Columns.Add(xnodattribute.Name.ToString()); cnt = 1; } } foreach (XmlNode xnodattribute1 in mapattributes) { dr[rows] = xnodattribute1.InnerText.ToString(); rows += 1; } dt.Rows.Add(dr); Session["dt"] = dt; } } else { if (Xnode.HasChildNodes) { XmlNodeList xnodelist = Xnode.ChildNodes; foreach (XmlNode xnode in xnodelist) { if (xnode.InnerText.ToLower() == TextBox1.Text.ToLower().ToString()) { if (cnt != 1) { foreach (XmlNode xnodelists in xnodelist) { dt.Columns.Add(xnodelists.Name.ToString()); cnt = 1; } } foreach (XmlNode xnodelist1 in xnodelist) { dr[rows] = xnodelist1.InnerText.ToString(); rows += 1; } dt.Rows.Add(dr); Session["dt"] = dt; } } } } if (Xnode.HasChildNodes) { Xnodeworking = Xnode.FirstChild; while (Xnodeworking != null) { AddCountry(Xnodeworking, intlevel + 1); Xnodeworking = Xnodeworking.NextSibling; } } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|