Sunday 15 March 2015

Use where condition for retrieving the xml data with C# -


I want to get data from an XML file. I am bringing the ID of the node from the previous page and on the next page I want to display the data from XML of that ID. I am using the ID query string of the node, but when I run my code, I get this error

System.Xml.XmlException: The data at the original level is invalid I Line 1 , Position 1.

This is my code

  XElement xid = XElement.Parse (Request.JQueryString ["ID"]); // var id = Request.QueryString ["id"]; Var doc = XDocument.Load (Server MapPath ("~ / Data / BlogContent.xml")); Var result = doc.Descendants ("Post"). Where (x = & gt; x.Element ("id") == xid). Value (x = & gt; new {id = x.Element ("id"). Value, title = x.Element ("title"). Value, description = x.Element ("Discription"). Value, DT = X.Element ("dt"). Value, mnt = x.Element ("mnt") value, yr = x.Element ("yr"). Value}). Orderbinding sensing (x = & x; x.id). Take (5); Repeater 1 Data source = results; Repeater1.DataBind ();   

This is my XML

  & lt ;? Xml version = "1.0" encoding = "UTF-8"? & Gt; & Lt; Content & gt; & Lt; Post & gt; & Lt; ID & gt; 1 & lt; / Id & gt; & Lt; Title & gt; FD & lt; / Title & gt; & Lt; Discription & gt; Fdsafsdf & lt; / Discription & gt; & Lt; DT & gt; 21 & lt; / Dt & gt; & Lt; MNT> 6 & lt; / MNT> & Lt; Years & gt; 2013 and lt; / Year & gt; & Lt; / Post & gt; & Lt; / Content & gt;   

Please tell me why I am wrong

The error does not indicate the line, but I bet it's the one:

  XElement xid = XElement.Parse (Request .JQueryString ["ID"]);   

The most likely "id" in your query string is any type of identifier, no XML - hence the error.

Something like this is what you want:

  string xid = request JQueryString ["ID"];   

Then you can use it in your where section.

In addition, there is an error in your section - you are trying to compare a XElement with a value - you value of the excelment value < Using code> property:

  where (x = & gt) must be used; X.Element ("id") value == xid)   

XElement.Value A string return - then simply assume the string from the query string. And use it in comparison to your section.

Keeps everything together

  string xid = Request.QueryString ["ID"]; Var doc = XDocument.Load (Server MapPath ("~ / Data / BlogContent.xml")); Results above = doc.Descendants ("post"). Where (x => x.Element ("id") value == xid) .Select (x = & gt; new {id = x.Element (" Value "," name ") .Value, title = x.Element (" title "). Value, Discription = x.Element (" Discription "). Value, DT = x.Element (" DT "). Value, MNT = x.Element ("MNT".) Value, year = x.Element ("year") value}) OrderByDescending (x => x.id) .te (5); Repeater 1 Data source = results; Repeater1.DataBind ();    

No comments:

Post a Comment