LINQ - parse xelement using linq to xml - Asked By Megha Nagpal on 04-May-12 08:49 AM

Earn up to 20 extra points for answering this tough question.
hi..
I want to get the value of errorcode  from the below mentioned xml

<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
  <Result ID="1,Delete">
    <ErrorCode>0x00000000</ErrorCode>
  </Result>
</Results>


this xml is retrieved in an XElement object

i want to retrieve the value of error code using linq to xml

Pls help me on this

Any help is appreciated.

Thanks in advance
Jitendra Faye replied to Megha Nagpal on 04-May-12 11:02 AM
Use this code-

var data = from xmldata in XElement.Load(Server.MapPath("XMLFile.xml")).Elements()
            select xmldata;
      foreach (var item in custs)
      {
        string value= item.Value;    //0x00000000
      }


TRy this and let me know
Jitendra Faye replied to Megha Nagpal on 04-May-12 11:06 AM
YOu can try like this also-


 String xml = @"<Results xmlns="http://schemas.microsoft.com/sharepoint/soap/">
  <Result ID="1,Delete">
    <ErrorCode>0x00000000</ErrorCode>
  </Result>
</Results>";

       
var test = XElement.Parse(xml)
               
.Descendants("ErrorCode")
               
.First()
               
.Value;


TRy this and let me know.
Chintan Vaghela replied to Megha Nagpal on 05-May-12 02:49 AM

Hello,

Fist take xml in string value

 

After then parse this string value to XElement

 

Now using linq query get ErrorCode value .

 

 

string ErrCode = "";
 
  
 
      string resultXML = @"<Results xmlns=""http://schemas.microsoft.com/sharepoint/soap/"">
 
            <Result ID=""1,Delete"">
 
              <ErrorCode>0x00000000</ErrorCode>
 
            </Result>
 
            </Results>";
 
      XElement xElementResult = XElement.Parse(resultXML);
 
  
 
      var varResult = (from res in xElementResult.Elements()
 
              select res.Value).FirstOrDefault();
 
  
 
      if (varResult != null)
 
      {
 
        ErrCode = varResult;
 
      }

 

 

 

Hope this helpful!

Thanks

 

 

 

[)ia6l0 iii replied to Megha Nagpal on 05-May-12 11:10 PM
Another permanent way to figure out how this works, and to learn more, is to use the MSDN samples on this very same topic. MSDN provides a good set of samples, that teach you the basics. Although it does not help you master them, it is good to kick start with that. 

MSDN has samples on "Linq To XML" at the following url:
http://msdn.microsoft.com/en-us/library/bb397987.aspx 

Hope this helps.
Megha Nagpal replied to Jitendra Faye on 07-May-12 12:30 AM
Thanks , it worked...
Megha Nagpal replied to Chintan Vaghela on 07-May-12 12:33 AM
Thanks , it worked...
Jitendra Faye replied to Megha Nagpal on 07-May-12 12:59 AM
you always welcome.